Windows上的Python - 如何等待多个子进程? [英] Python on Windows - how to wait for multiple child processes?

查看:144
本文介绍了Windows上的Python - 如何等待多个子进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何等待Windows上Python中的多个子进程,没有主动等(轮询)?事情是这样的几乎的工作对我来说:

How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this almost works for me:

proc1 = subprocess.Popen(['python','mytest.py'])
proc2 = subprocess.Popen(['python','mytest.py'])    
proc1.wait()
print "1 finished"
proc2.wait()
print "2 finished"

问题是,当 PROC2 PROC1 结束,父进程将仍然等待 PROC1 。在Unix人会使用 waitpid函数(0)在一个循环中获得子进程的回归codeS为他们完成 - 如何实现在Python这样的事情在Windows ?

The problem is that when proc2 finishes before proc1, the parent process will still wait for proc1. On Unix one would use waitpid(0) in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?

推荐答案

这似乎矫枉过正,但这里有云:

It might seem overkill, but, here it goes:

import Queue, thread, subprocess

results= Queue.Queue()
def process_waiter(popen, description, que):
    try: popen.wait()
    finally: que.put( (description, popen.returncode) )
process_count= 0

proc1= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
    (proc1, "1 finished", results))
process_count+= 1

proc2= subprocess.Popen( ['python', 'mytest.py'] )
thread.start_new_thread(process_waiter,
    (proc2, "2 finished", results))
process_count+= 1

# etc

while process_count > 0:
    description, rc= results.get()
    print "job", description, "ended with rc =", rc
    process_count-= 1

这篇关于Windows上的Python - 如何等待多个子进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆