将子流程输出到PIPE并直接输出到stdout



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

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

目前我的做法如下:

p = subprocess.Popen( command_list, stdout=subprocess.PIPE, 
stderr=subprocess.PIPE )
out, error_msg = p.communicate()
print out + "nn" + error_msg
#next comes code in which I check out and error_msg

但是这种方法的缺点是用户在进程运行时看不到进程的输出。仅在最后打印输出。

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

注意:我目前正在开发python2.5(使用此python版本的旧软件版本)。

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

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

最新更新