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

发布于 2021-02-02 23:17:58

为了从我的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"),我的程序将等待直到该过程完成为止,然后我才能获得程序的完整输出。如果我正在运行需要一段时间才能完成的过程,这将很烦人。

我可以让我的程序通过在循环完成之前轮询过程输出来逐行写过程输出吗?

关注者
0
被浏览
78
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    你可以在命令输出行之后立即使用iter处理行lines = iter(fd.readline, "")。这是显示典型用例的完整示例:

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看