要从我的 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/