Python 的 redirect_stdout() 为什么抓不到子进程输出?

季宁
季宁
发布时间:2026-12-01 | 785人浏览过
原创

对比父进程的 Python 输出重定向与子进程的管道捕获,从 subprocess.run 的返回值读取标准输出。

将 print() 改为写入内存后,同一 with 块内的子进程仍可能在终端打印。这是因为 redirect_stdout() 仅替换父进程的 Python 输出流。若要将子进程输出读入变量,需在启动时配置捕获。

父进程和子进程写入哪里

redirect_stdout(buffer) 在块内把父进程的 sys.stdout 指向 StringIO,使父进程的 print("parent") 写入内存。首次启动子进程时,subprocess.run() 使用默认的 stdout=None,子进程继承操作系统的标准输出。若脚本在普通终端运行,子进程会将该行输出到终端。

父进程的 parent 写入 StringIO,默认启动的子进程将 child 写向继承的标准输出。
替换父进程的 Python 流后,子进程默认仍继承原有的系统标准输出。

启动时为子进程接上输出管道

第二次调用为 subprocess.run() 添加 capture_output=True,分别为标准输出和标准错误连接管道。text=True 启用文本模式,子进程标准输出以字符串形式存于 result.stdout,标准错误可从 result.stderr 读取。示例使用本机 Python 解释器执行两次相同的打印命令。

启用捕获后,子进程的 stdout 和 stderr 分别进入两个管道,再写入返回对象的对应属性。
标准输出和标准错误各有一个管道,可以从返回对象分别读取。
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'
预期输出依次显示 child、redirected 读到 parent、captured 读到 child。
第一行由子进程直接打印,后两行是父进程读出的字符串表示。

只捕获标准输出时怎么写

若只需读取标准输出且希望标准错误照常显示,可将第二次调用的 capture_output=True 替换为 stdout=subprocess.PIPE 并保留 text=True。此时标准错误按默认方式继承。由于 capture_output=True 已同时配置两个管道,调用时不得叠加使用 stdout 或 stderr 参数。

相关专题:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表