在进程运行时不断打印子进程输出 [英] Constantly print Subprocess output while process is running

查看:81
本文介绍了在进程运行时不断打印子进程输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

To launch programs from my Python-scripts, I'm using the following method:

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") 这样的进程时,我的程序会一直等到该进程完成,然后才能获得程序的完整输出.如果我正在运行一个需要一段时间才能完成的进程,这会很烦人.

So when i launch a process like Process.execute("mvn clean install"), my program waits until the process is finished, and only then i get the complete output of my program. This is annoying if i'm running a process that takes a while to finish.

我可以让我的程序通过在循环结束之前轮询进程输出或其他方式来逐行写入进程输出吗?

Can I let my program write the process output line by line, by polling the process output before it finishes in a loop or something?

我发现了这篇可能相关的文章.

I found this article which might be related.

推荐答案

您可以使用 iter 在命令输出后立即处理行:lines = iter(fd.readline, "").这是一个显示典型用例的完整示例(感谢@jfs 提供帮助):

You can use iter to process lines as soon as the command outputs them: lines = iter(fd.readline, ""). Here's a full example showing a typical use case (thanks to @jfs for helping out):

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="")

这篇关于在进程运行时不断打印子进程输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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