Python on Windows - how to wait for multiple child processes?

前端 未结 6 1371
滥情空心
滥情空心 2020-12-05 18:12

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

proc1 = subpr         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 18:58

    Twisted on Windows will perform an active wait under the covers. If you don't want to use threads, you will have to use the win32 API to avoid polling. Something like this:

    import win32process
    import win32event
    
    # Note: CreateProcess() args are somewhat cryptic, look them up on MSDN
    proc1, thread1, pid1, tid1 = win32process.CreateProcess(...)
    proc2, thread2, pid2, tid2 = win32process.CreateProcess(...)
    thread1.close()
    thread2.close()
    
    processes = {proc1: "proc1", proc2: "proc2"}
    
    while processes:
        handles = processes.keys()
        # Note: WaitForMultipleObjects() supports at most 64 processes at a time
        index = win32event.WaitForMultipleObjects(handles, False, win32event.INFINITE)
        finished = handles[index]
        exitcode = win32process.GetExitCodeProcess(finished)
        procname = processes.pop(finished)
        finished.close()
        print "Subprocess %s finished with exit code %d" % (procname, exitcode)
    

提交回复
热议问题