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"),
我的程序将等待直到该过程完成为止,然后我才能获得程序的完整输出。如果我正在运行需要一段时间才能完成的过程,这将很烦人。
我可以让我的程序通过在循环完成之前轮询过程输出来逐行写过程输出吗?
-
你可以在命令输出行之后立即使用
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="")