python - 用python的子进程同时捕获并输出stderr

标签 python subprocess pipe stdout stderr

(目前使用python 3.2)

我需要能够:

  • 使用子进程运行命令
  • 该命令的 stdout/stderr 都需要实时打印到终端(无论它们是否都出现在 stdout 或 stderr 或其他什么上都无关紧要
  • 与此同时,我需要一种方法来了解该命令是否向 stderr 打印了任何内容(最好是它打印的内容)。

我尝试过子进程管道,在 bash 中进行奇怪的管道重定向,以及使用 tee,但到目前为止还没有找到任何可行的方法。这是可能的吗?

最佳答案

我的解决方案:

import subprocess

process = subprocess.Popen("my command", shell=True,
                           stdout=None, # print to terminal
                           stderr=subprocess.PIPE)
duplicator = subprocess.Popen("tee /dev/stderr", shell=True, # duplicate input stream
                              stdin=process.stderr, 
                              stdout=subprocess.PIPE, # catch error stream of first process
                              stderr=None) # print to terminal
error_stream = duplicator.stdout
print('error_stream.read() = ' + error_stream.read())

关于python - 用python的子进程同时捕获并输出stderr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12886136/

相关文章:

python - 如何使用子进程拦截 "pipenv install"spinner-like 输出消息?

python - 错误 Python 子进程调用复制文件。没有文件,失败,但返回 1。为什么?

python - 运行时警告 : invalid value encountered in maximum

Python 假设 - 为多次测试构建一次策略?

python - 2D高斯拟合在Python中某些坐标处的强度

python - Python 中的管道 SoX - 子进程替代方案?

c - C shell 管系统

c - 提示如何早于 popen 调用的标准输出出现?

c - 多管道不起作用

python - SQLAlchemy 子类/继承关系