10

I am using a python script to run a process using subprocess.Popen and simultaneously store the output in a text file as well as print it on the console. This is my code:

result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in result.stdout.readlines(): #read and store result in log file
    openfile.write("%s\n" %line)
    print("%s" %line)

Above code works fine, but what it does is it first completes the process and stores the output in result variable. After that for loop stores the output as well as print it.

But i want the output at runtime (as my process can take hours to complete, i don't get any output for all these hours).

So is there any other function that gives me the output dynamically (at runtime), means as soon as the process gives first line, it should get printed.

4

3 回答 3

7

这里的问题是.readlines()在返回之前获取整个输出,因为它构造了一个完整的列表。直接迭代即可:

for line in result.stdout:
    print line
于 2013-05-15T06:52:46.523 回答
4

.readlines()返回进程在打开时将返回的所有行的列表,即,在收到子进程的所有输出之前,它不会返回任何内容。要“实时”逐行读取:

import sys
from subprocess import Popen, PIPE

proc = Popen(cmd, shell=True, bufsize=1, stdout=PIPE)
for line in proc.stdout:
    openfile.write(line)
    sys.stdout.buffer.write(line)
    sys.stdout.buffer.flush()
proc.stdout.close()
proc.wait()

注意:如果子进程在非交互模式下运行时使用块缓冲;您可能需要pexpect,pty模块stdbuf, unbuffer,script命令

注意:在 Python 2 上,您可能还需要使用iter(), 来获得“实时”输出:

for line in iter(proc.stdout.readline, ""):
    openfile.write(line)
    print line,
于 2013-05-15T09:17:31.403 回答
1

您可以通过readline在管道上使用来逐行迭代:

while True: 
    line = result.stdout.readline()
    print line.strip()
    if not line:
        break

这些行包含\n我为打印而剥离的尾随。当进程终止时,readline 返回一个空字符串,因此您知道何时停止。

于 2013-05-15T06:36:54.030 回答