我正在并行运行来自 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++ 脚本并执行它。
最佳答案
如果您的平台不是 Windows,您可能会针对子进程的标准输出管道进行选择。然后,您的应用将被阻止,直到:
- 其中一个已注册的文件描述符有一个 I/O 事件(在这种情况下,我们对子进程的标准输出管道上的挂起感兴趣)
- 投票超时
在 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
关于python - 等待具有多个并行作业的子进程结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3194018/