简体   繁体   English

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

[英]Output of subprocess both to PIPE and directly to stdout

I found a number of questions which looks like mine, but which did not produce a solution I can use (closest is: subprocess output to stdout and to PIPE ) 我发现了一些看起来像我的问题但是没有产生我可以使用的解决方案(最接近的是: 子程序输出到stdout和PIPE

The problem: I want to start a process using subprocess which takes a long time. 问题:我想使用子进程启动一个进程需要很长时间。 After running the command I need to parse the stdout-output and the stderr-output. 运行命令后,我需要解析stdout-output和stderr-output。

Currently I do it as follows: 目前我这样做如下:

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

But the drawback of this method is that the user does not see the output of the process while it is running. 但是这种方法的缺点是用户在运行时看不到进程的输出。 Only at the end the output is printed. 仅在结尾处打印输出。

Is there a way that the output is printed while the command is running (as if I gave the command without stdout/stderr=subprocess.PIPE) and still have the output via p.communicate in the end? 有没有办法在命令运行时打印输出(好像我给出了没有stdout / stderr = subprocess.PIPE的命令)并且最后还是通过p.communicate输出?

Note: I'm currently developing on python 2.5 (old software release which uses this python version). 注意:我目前正在开发python 2.5(使用此python版本的旧软件版本)。

This snippet has helped me once in a similar situation: 在类似的情况下,这段代码曾帮助过我:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM