Python 的 redirect_stdout() 为什么抓不到子进程输出?
对比父进程的 Python 输出重定向与子进程的管道捕获,从 subprocess.run 的返回值读取标准输出。
将 print() 改为写入内存后,同一 with 块内的子进程仍可能在终端打印。这是因为 redirect_stdout() 仅替换父进程的 Python 输出流。若要将子进程输出读入变量,需在启动时配置捕获。
父进程和子进程写入哪里
redirect_stdout(buffer) 在块内把父进程的 sys.stdout 指向 StringIO,使父进程的 print("parent") 写入内存。首次启动子进程时,subprocess.run() 使用默认的 stdout=None,子进程继承操作系统的标准输出。若脚本在普通终端运行,子进程会将该行输出到终端。
启动时为子进程接上输出管道
第二次调用为 subprocess.run() 添加 capture_output=True,分别为标准输出和标准错误连接管道。text=True 启用文本模式,子进程标准输出以字符串形式存于 result.stdout,标准错误可从 result.stderr 读取。示例使用本机 Python 解释器执行两次相同的打印命令。
from contextlib import redirect_stdout
from io import StringIO
import subprocess
import sys
command = [sys.executable, "-c", "print('child')"]
buffer = StringIO()
with redirect_stdout(buffer):
print("parent")
subprocess.run(command, check=True)
result = subprocess.run(
command,
capture_output=True,
text=True,
check=True,
)
print("redirected:", repr(buffer.getvalue()))
print("captured:", repr(result.stdout))
从三行输出分清两个去向
预期第一行 child 来自首次运行,直接输出至终端。第二行展示 buffer.getvalue() 的表示形式,仅包含父进程写入的 parent 及换行符。第三行展示 result.stdout 的表示形式,包含第二次运行捕获的 child 及换行符。
预期输出
child
redirected: 'parent\n'
captured: 'child\n'
只捕获标准输出时怎么写
若只需读取标准输出且希望标准错误照常显示,可将第二次调用的 capture_output=True 替换为 stdout=subprocess.PIPE 并保留 text=True。此时标准错误按默认方式继承。由于 capture_output=True 已同时配置两个管道,调用时不得叠加使用 stdout 或 stderr 参数。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













