3

(目前使用python 3.2)

我需要能够:

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

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

4

2 回答 2

2

我的解决方案:

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())
于 2012-10-14T21:38:20.510 回答
0

尝试这样的事情:

import os

cmd = 'for i in 1 2 3 4 5; do sleep 5; echo $i; done'
p = os.popen(cmd)

while True:
    output = p.readline()
    print(output)
    if not output: break

在 python2 中,您也可以通过以下方式轻松捕获 stderr popen3

i, o, err = os.popen3(cmd)

但是python3中似乎没有这样的功能。如果您找不到解决方法,请尝试subprocess.Popen直接使用,如下所述:http: //www.saltycrane.com/blog/2009/10/how-capture-stdout-in-real-time-python/

于 2012-10-14T21:35:30.990 回答