子流程既输出到PIPE,又直接输出到stdout

Nem*_*lis 5 python subprocess

我发现了许多看起来像我的问题,但是没有产生我可以使用的解决方案(最近的问题是:子进程输出到stdout和PIPE

问题:我想使用需要很长时间的子流程来启动流程。运行命令后,我需要解析stdout-output和stderr-output。

目前,我这样做如下:

p = subprocess.Popen( command_list, stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE )
out, error_msg = p.communicate()
print out + "\n\n" + error_msg

#next comes code in which I check out and error_msg
Run Code Online (Sandbox Code Playgroud)

但是此方法的缺点是,用户在运行过程中看不到该过程的输出。仅在最后输出。

有没有一种方法可以在命令运行时打印输出(就像我给出的命令没有stdout / stderr = subprocess.PIPE一样),并且最终还是通过p.communicate输出?

注意:我目前正在使用python 2.5(使用此python版本的旧软件版本)进行开发。

Sci*_*cis 8

这个片段曾经在类似的情况下帮助过我:

process = subprocess.Popen(cmd, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
    print line,
    sys.stdout.flush() # please see comments regarding the necessity of this line 
process.wait()
errcode = process.returncode
Run Code Online (Sandbox Code Playgroud)