(目前使用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/