进程运行时不断打印子进程输出

要从我的Python脚本启动程序,我使用以下方法:

def execute(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = process.communicate()[0]
    exitCode = process.returncode

    if (exitCode == 0):
        return output
    else:
        raise ProcessException(command, exitCode, output)

所以当我启动一个像Process.execute("mvn clean install")这样的进程时,我的程序会一直等到进程结束,然后才能得到我程序的完整输出。 如果我正在运行需要一段时间才能完成的流程,这很烦人。

我可以让我的程序逐行写入过程输出,在循环结束之前轮询过程输出吗?

** [编辑]对不起,我发布这个问题之前没有很好的搜索。 线程实际上是关键。 在这里找到一个示例来演示如何执行它:** Python Subprocess.Popen从一个线程


只要命令输出它们,就可以使用iter来处理行: lines = iter(fd.readline, "") 。 下面是一个完整的示例,展示了一个典型的用例(感谢@JF Sebastian的帮助):

from __future__ import print_function # Only Python 2.x
import subprocess

def execute(cmd):
    popen = subprocess.Popen(cmd, stdout=subprocess.PIPE, universal_newlines=True)
    for stdout_line in iter(popen.stdout.readline, ""):
        yield stdout_line 
    popen.stdout.close()
    return_code = popen.wait()
    if return_code:
        raise subprocess.CalledProcessError(return_code, cmd)

# Example
for path in execute(["locate", "a"]):
    print(path, end="")

好吧,我设法解决它没有线程(任何建议,为什么使用线程会更好,赞赏)通过使用这个问题的代码片段在运行时拦截子进程的标准输出

def execute(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # Poll process for new output until finished
    while True:
        nextline = process.stdout.readline()
        if nextline == '' and process.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()

    output = process.communicate()[0]
    exitCode = process.returncode

    if (exitCode == 0):
        return output
    else:
        raise ProcessException(command, exitCode, output)

要在Python 3中刷新stdout缓冲区时逐行输出子进程的输出:

from subprocess import Popen, PIPE, CalledProcessError

with Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p:
    for line in p.stdout:
        print(line, end='') # process line here

if p.returncode != 0:
    raise CalledProcessError(p.returncode, p.args)

注意:你不需要p.poll() - 到达eof时循环结束。 你不需要它iter(p.stdout.readline, '') - iter(p.stdout.readline, '')读错误在Python 3中得到了修复。

另请参阅Python:从subprocess.communicate()读取流式输入。

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

上一篇: Constantly print Subprocess output while process is running

下一篇: subprocess output to stdout and to PIPE