等待多个并行作业的子进程结束

时间:2010-07-07 10:55:31

标签: python subprocess

我正在并行运行python中的一些子进程。我想等到每个子进程都完成了。我正在做一个不优雅的解决方案:

runcodes = ["script1.C", "script2.C"]
ps = []
for script in runcodes:
  args = ["root", "-l", "-q", script]
  p = subprocess.Popen(args)
  ps.append(p)
while True:
  ps_status = [p.poll() for p in ps]
  if all([x is not None for x in ps_status]):
    break

是否有一个可以处理多个子进程的类?问题是wait方法会阻止我的程序。

更新:我想在计算过程中显示进度:类似“4/7子流程完成......”

如果你很好奇root编译c ++脚本并执行它。

4 个答案:

答案 0 :(得分:9)

如果您的平台不是Windows,则可以选择子进程的stdout管道。然后你的应用会阻止,直到:

  • 其中一个已注册的文件描述符有一个I / O事件(在这种情况下,我们对子进程的stdout管道上的挂断感兴趣)
  • 民意调查超时

在Linux 2.6.xx上使用epoll的非充实示例:

import subprocess
import select

poller = select.epoll()
subprocs = {} #map stdout pipe's file descriptor to the Popen object

#spawn some processes
for i in xrange(5):
    subproc = subprocess.Popen(["mylongrunningproc"], stdout=subprocess.PIPE)
    subprocs[subproc.stdout.fileno()] = subproc
    poller.register(subproc.stdout, select.EPOLLHUP)

#loop that polls until completion
while True:
    for fd, flags in poller.poll(timeout=1): #never more than a second without a UI update
        done_proc = subprocs[fd]
        poller.unregister(fd)
        print "this proc is done! blah blah blah"
        ...  #do whatever
    #print a reassuring spinning progress widget
    ...
    #don't forget to break when all are done

答案 1 :(得分:8)

你可以这样做:

runcodes = ["script1.C", "script2.C"]

ps = []
for script in runcodes:
    args = ["root", "-l", "-q", script]
    p = subprocess.Popen(args)
    ps.append(p)

for p in ps:
    p.wait()

流程将并行运行,您将在最后等待所有流程。

答案 2 :(得分:7)

怎么样

import os, subprocess
runcodes = ["script1.C", "script2.C"]
ps = {}
for script in runcodes:
    args = ["root", "-l", "-q", script]
    p = subprocess.Popen(args)
    ps[p.pid] = p
print "Waiting for %d processes..." % len(ps)
while ps:
    pid, status = os.wait()
    if pid in ps:
        del ps[pid]
        print "Waiting for %d processes..." % len(ps)

答案 3 :(得分:0)

我认为答案不是python代码或语言功能,而是系统功能,请考虑以下解决方案:

runcodes = ["script1.C", "script2.C"]

Args = []
for script in runcodes:
    Args += " ".join(["root", "-l", "-q", script])


P = subprocess.Popen(" & ".join(Args))
P.wait()