子进程输出到 PIPE 和直接输出到标准输出 [英] Output of subprocess both to PIPE and directly to stdout

查看:47
本文介绍了子进程输出到 PIPE 和直接输出到标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一些看起来像我的问题,但没有产生我可以使用的解决方案(最接近的是:子进程输出到标准输出和管道)

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-output 和 stderr-output.

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.

目前我是这样做的:

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.

有没有办法在命令运行时打印输出(就像我在没有 stdout/stderr=subprocess.PIPE 的情况下给出命令一样)并且最后仍然通过 p.communicate 输出?

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?

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

Note: I'm currently developing on python 2.5 (old software release which uses this python version).

推荐答案

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

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

这篇关于子进程输出到 PIPE 和直接输出到标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆