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)

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.

Currently I do it as follows:

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

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?

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


这段代码曾经帮助我处理过类似的情况:

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

Use | tee | tee

import subprocess

# Run command and redirect it by | tee to a file named out.txt 
p = subprocess.Popen([command, '|', 'tee', 'out.txt'])
p.wait()

# Get standard output
f = open('out.txt')
out = f.read()
f.close()

print out

In windows platform, there is no | tee | tee . We need to use Powershell. So the command at the third line becomes:

# Run command in PowerShell and redirect it by | tee to a file named out.txt 
p = subprocess.Popen(['powershell','command, '|', 'tee', 'out.txt'])

By this way, the output is printed and the output will also be stored in out.

链接地址: http://www.djcxy.com/p/13482.html

上一篇: 循环中的python popen管道

下一篇: 子过程输出到PIPE并直接输出到stdout