如果要并行运行多个进程,然后在它们产生结果时对其进行处理,可以使用如下所示的轮询:from subprocess import Popen, PIPE
import time
running_procs = [
Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]
while running_procs:
for proc in running_procs:
retcode = proc.poll()
if retcode is not None: # Process finished.
running_procs.remove(proc)
break
else: # No process is done, wait a bit and check again.
time.sleep(.1)
continue
# Here, `proc` has finished with return code `retcode`
if retcode != 0:
"""Error handling."""
handle_results(proc.stdout)
那里的控制流有点复杂,因为我试图使它变小——你可以根据自己的喜好重构。:-)
这有一个优势,即首先为早期完成请求提供服务。如果您在第一个运行的进程上调用communicate,结果发现运行时间最长,则其他运行的进程在您可以处理其结果时将一直处于空闲状态。