Windows上的Python-如何等待多个子进程?

2024-05-20 16:46:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Windows上的Python中等待多个子进程,而不进行活动等待(polling)?像这样的东西几乎对我有效:

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

问题是,当proc2proc1之前完成时,父进程仍将等待proc1。在Unix上,人们会在循环中使用waitpid(0)来获取子进程完成时的返回代码-如何在Windows上的Python中实现这样的功能?


Tags: 代码py进程windowsunixsubprocessprintpopen
3条回答

看起来有点过头了,但是,这里有:

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

基于zseil的答案,您可以通过混合使用子进程和win32 API调用来实现这一点。我使用了直接的ctypes,因为我的Python没有安装win32api。我只是从MSYS中生成sleep.exe作为一个例子,但是很明显你可以生成任何你喜欢的进程。我使用OpenProcess()从进程的PID中获取一个句柄,然后WaitForMultipleObjects等待任何进程完成。

import ctypes, subprocess
from random import randint
SYNCHRONIZE=0x00100000
INFINITE = -1
numprocs = 5
handles = {}

for i in xrange(numprocs):
    sleeptime = randint(5,10)
    p = subprocess.Popen([r"c:\msys\1.0\bin\sleep.exe", str(sleeptime)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
    h = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE, False, p.pid)
    handles[h] = p.pid
    print "Spawned Process %d" % p.pid

while len(handles) > 0:
    print "Waiting for %d children..." % len(handles)
    arrtype = ctypes.c_long * len(handles)
    handle_array = arrtype(*handles.keys())
    ret = ctypes.windll.kernel32.WaitForMultipleObjects(len(handle_array), handle_array, False, INFINITE)
    h = handle_array[ret]
    ctypes.windll.kernel32.CloseHandle(h)
    print "Process %d done" % handles[h]
    del handles[h]
print "All done!"

Twisted有一个在Windows上工作的asynchronous process-spawning API。实际上有几个不同的实现,其中许多不是很好,但您可以在它们之间切换,而不必更改代码。

相关问题 更多 >