猿问

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

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

为了从我的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"),我的程序等待进程完成,只有这样,我才能得到程序的完整输出。如果我正在运行一个需要一段时间才能完成的进程,这是很烦人的。

我能让我的程序逐行地写进程输出,在流程输出完成之前轮询它吗?

*[编辑]对不起,在发布这个问题之前,我搜索得不太好。线程实际上是关键。在这里找到一个例子,说明如何做到这一点:*从线程打开


三国纷争
浏览 567回答 3
3回答

largeQ

你可以用ITER若要在命令输出行时立即处理这些行,请执行以下操作:lines = iter(fd.readline, "")..下面是一个完整的示例,展示了一个典型的用例(感谢@JFS帮助):from __future__ import print_function # Only Python 2.ximport subprocessdef 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)# Examplefor path in execute(["locate", "a"]):     print(path, end="")

慕少森

好的,我设法在没有线程的情况下解决了这个问题(如果建议使用线程会更好),可以使用这个问题中的一个片段。在子进程运行时拦截子进程的stdoutdef execute(command):     process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)     # Poll process for new output until finished     while True:         nextline = process.stdout.readline()         if nextline == '' and process.poll() is not None:             break         sys.stdout.write(nextline)         sys.stdout.flush()     output = process.communicate()[0]     exitCode = process.returncode    if (exitCode == 0):         return output    else:         raise ProcessException(command, exitCode, output)

慕虎7371278

在Python 3中刷新其标准输出缓冲区后,立即逐行打印子进程的输出:from subprocess import Popen, PIPE, CalledProcessErrorwith Popen(cmd, stdout=PIPE, bufsize=1, universal_newlines=True) as p:     for line in p.stdout:         print(line, end='') # process line hereif p.returncode != 0:     raise CalledProcessError(p.returncode, p.args)注意:你不需要p.poll()-当到达eof时,循环结束。你不需要iter(p.stdout.readline, '')-在Python 3中修复了预读错误.也看,Python:从子流程读取流输入。Communications().
随时随地看视频慕课网APP

相关分类

Python
我要回答