答案:使用subprocess.run()并传入命令列表、capture_output=True、text=True和check=True,可安全执行外部命令并捕获输出。通过异常处理获取返回码和错误信息,避免shell=True以防注入风险,复杂场景改用Popen进行异步管理与交互。

要在Python中启动一个子进程,最直接也最推荐的方式是使用内置的
subprocess
对于大多数简单的场景,比如执行一个外部命令并等待它完成,
subprocess.run()
举个例子,你想列出当前目录的文件:
import subprocess
# 最简单的用法
# capture_output=True 捕获输出
# text=True 将输出解码为字符串
# check=True 确保命令成功执行(非零返回码抛出异常)
try:
result = subprocess.run(['ls', '-l'], capture_output=True, text=True, check=True)
print("命令成功执行,输出如下:")
print(result.stdout)
except subprocess.CalledProcessError as e:
print(f"命令执行失败,返回码:{e.returncode}")
print(f"错误输出:{e.stderr}")
except FileNotFoundError:
print("命令未找到,请检查系统路径或命令是否存在。")
这里有几个关键点:
立即学习“Python免费学习笔记(深入)”;
['ls', '-l']
shell=True
capture_output=True
text=True
encoding='utf-8'
check=True
check=True
subprocess.run()
CalledProcessError
如果你需要执行一个更复杂的命令,或者需要shell的特性,比如管道:
import subprocess
# 使用shell=True,但要非常谨慎
try:
result = subprocess.run('echo hello | grep he', shell=True, capture_output=True, text=True, check=True)
print("命令成功执行,输出如下:")
print(result.stdout.strip())
except subprocess.CalledProcessError as e:
print(f"命令执行失败: {e}")
print(f"Stderr: {e.stderr}")
except FileNotFoundError:
print("命令未找到,请检查系统路径或命令是否存在。")请记住,
shell=True
安全性和输出捕获是使用
subprocess
shell=True
关于安全性,核心原则是:永远优先使用列表形式传递命令和参数。
# 安全的做法:命令和参数分开,作为列表传递
command_parts = ['git', 'clone', 'https://github.com/user/repo.git']
try:
subprocess.run(command_parts, check=True)
print("Git clone 命令执行成功。")
except subprocess.CalledProcessError as e:
print(f"Git clone 失败,返回码: {e.returncode}")
# 这里可以进一步捕获并打印 stderr
except FileNotFoundError:
print("Git 命令未找到,请检查是否已安装Git。")
# 危险的做法 (如果repo_url来自用户输入,可能被注入恶意命令)
# repo_url = "https://github.com/user/repo.git; rm -rf /"
# subprocess.run(f"git clone {repo_url}", shell=True)当命令和参数作为列表传递时,Python会直接调用底层的操作系统API(如
execvp
至于捕获输出,
capture_output=True
import subprocess
try:
process_result = subprocess.run(
['ping', '-c', '4', 'google.com'], # Linux/macOS ping
# ['ping', 'google.com', '-n', '4'], # Windows ping
capture_output=True,
text=True, # 自动解码为字符串
check=True # 非零返回码时抛异常
)
print("Standard Output:")
print(process_result.stdout)
print("\nStandard Error (if any):")
print(process_result.stderr)
except subprocess.CalledProcessError as e:
print(f"命令执行失败,返回码: {e.returncode}")
print(f"错误输出: {e.stderr}")
except FileNotFoundError:
print("命令未找到,请检查路径或是否已安装。")这里我通常会加上
check=True
CalledProcessError
ping
FileNotFoundError
当你的子进程不是“一锤子买卖”,而是需要长时间运行、异步操作或者需要父子进程之间进行持续交互时,
subprocess.run()
subprocess.Popen
Popen
一个典型的场景是启动一个后台服务,或者执行一个需要定时检查进度的脚本:
import subprocess
import time
import sys
# 假设有一个 count.py 文件内容如下:
# import time, sys
# for i in range(3):
# print(f"Count: {i}", file=sys.stderr) # 输出到stderr,方便区分
# time.sleep(1)
# print("Done counting!", file=sys.stderr)
print("父进程:启动子进程...")
# 使用 Popen,注意 stdin, stdout, stderr 的设置
# subprocess.PIPE 会创建管道,允许父进程读写
process = subprocess.Popen(
[sys.executable, 'count.py'], # 使用 sys.executable 确保找到当前Python解释器
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True # 同样为了方便处理文本
)
print("父进程:子进程已启动,我去做别的事情...")
time.sleep(1.5) # 父进程模拟做其他工作
print("父进程:检查子进程状态...")
# poll() 方法检查子进程是否已终止,如果终止则返回其返回码,否则返回 None
if process.poll() is None:
print("父进程:子进程仍在运行。")
else:
print(f"父进程:子进程已结束,返回码: {process.returncode}")
# 等待子进程完成并获取其输出
# communicate() 会等待子进程结束,并返回其stdout和stderr
stdout, stderr = process.communicate(timeout=5) # 设置超时,避免无限等待
print("\n父进程:子进程标准输出:")
print(stdout)
print("\n父进程:子进程标准错误输出:")
print(stderr)
if process.returncode != 0:
print(f"父进程:子进程以非零返回码 {process.returncode} 退出,可能存在问题。")Popen
communicate()
communicate(input=...)
对于更复杂的交互,比如需要实时读取子进程的输出,你可以直接操作
process.stdout
process.stderr
readline()
select
子进程执行失败或者结果不符合预期,这是开发中很常见的问题。我的经验是,大部分时候问题出在环境、权限或者命令本身上,而不是
subprocess
returncode
stderr
以上就是Python怎么启动一个子进程_subprocess模块子进程管理的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号