有些进程在很长一段时间后退出,它们的状态不断地被写入STDOUT。
如何在不等待进程退出的情况下运行进程并读取其 STDOUT?
我试过:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
o = p.communicate()[0] # Waits until process exits, also tried p.stdout.read()
print o # Isn't printed until process exists
do_something(o) # Doesn't get executed until process exits
请您参考如下方法:
逐行阅读很简单
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
for line in p.stdout:
do work here
p.wait()
if p.returncode != 0:
panic here
...主要是。命令倾向于以不同方式缓冲,这取决于它们是从控制台还是从其他程序运行。由于您不是控制台,您可能会发现它的输出频率较低......但它最终会在程序退出之前到达那里。在 linux 上,您可以使用 pty 或 pexpect 或其他东西,但我知道在 windows 上没有好的解决方案。
现在,如果您想并行运行它们,请为您运行的每个命令创建一个线程,并在编程结束时为每个命令创建一个 thread.join()。这本身就有点棘手。您可以使用线程池(请参阅 python 2.x 上的 multiprocessing.ThreadPool,不记得 3.x 中的名称)。
