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

前端 未结 6 1373
滥情空心
滥情空心 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 19:04

    You can use psutil:

    >>> import subprocess
    >>> import psutil
    >>> 
    >>> proc1 = subprocess.Popen(['python','mytest.py'])
    >>> proc2 = subprocess.Popen(['python','mytest.py'])    
    >>> ls = [psutil.Process(proc1.pid), psutil.Process(proc2.pid)]
    >>>
    >>> gone, alive = psutil.wait_procs(ls, timeout=3)
    

    'gone' and 'alive' are lists indicating which processes are gone and which ones are still alive.

    Optionally you can specify a callback which gets invoked every time one of the watched processes terminates:

    >>> def on_terminate(proc):
    ...     print "%s terminated" % proc
    ...
    >>> gone, alive = psutil.wait_procs(ls, timeout=3, callback=on_terminate)
    

提交回复
热议问题