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

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

我可以让我的程序通过在循环完成之前轮询进程输出或其他方式,让我的程序逐行编写进程输出吗?

我找到了 this可能相关的文章。

最佳答案

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

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

https://stackoverflow.com/questions/4417546/

相关文章:

linux - Mac 和 Linux 上的文本文件中的递归搜索和替换

python - pandas 获取不在其他数据框中的行

linux - 在 Linux 脚本中隐藏终端上的用户输入

python - 如何在使用 Python 插入 MySQL 数据库后获取 "id"?

linux - 没有行号的 Bash 历史记录

linux - 检索最后 100 行日志

python - 将元组转换为列表并返回

linux - 如何删除具有特定名称的文件夹

linux - 如何在 Bash 中运行超时的进程?

python - Windows Scipy 安装 : No Lapack/Blas Resourc