等待第一个子进程完成 [英] Wait for the first subprocess to finish
问题描述
我有一个 subprocess
进程列表.我不与他们沟通,只是等待.
I have a list of subprocess
' processes. I do not communicate with them and just wait.
我想等待第一个进程完成(此解决方案有效):
I want to wait for the first process to finish (this solution works):
import subprocess
a = subprocess.Popen(['...'])
b = subprocess.Popen(['...'])
# wait for the first process to finish
while True:
over = False
for child in {a, b}:
try:
rst = child.wait(timeout=5)
except subprocess.TimeoutExpired:
continue # this subprocess is still running
if rst is not None: # subprocess is no more running
over = True
break # If either subprocess exits, so do we.
if over:
break
我不想使用 os.wait()
,因为它可能从另一个 subprocess
返回,而不是我正在等待的列表的一部分.
I don't want use os.wait()
, cause it could return from another subprocess
not part of the list I'm waiting for.
一个好的和优雅的解决方案可能是使用 epoll
或 select 并且没有任何循环.
A nice and elegant solution would probably be with an epoll
or select and without any loop.
推荐答案
这是一个使用 psutil 的解决方案 - 它正是针对这个用例:
Here's a solution using psutil - which is aimed exactly at this use-case:
import subprocess
import psutil
a = subprocess.Popen(['/bin/sleep', "2"])
b = subprocess.Popen(['/bin/sleep', "4"])
procs_list = [psutil.Process(a.pid), psutil.Process(b.pid)]
def on_terminate(proc):
print("process {} terminated".format(proc))
# waits for multiple processes to terminate
gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
或者,如果您希望循环等待其中一个进程完成:
Or, if you'd like to have a loop waiting for one of the process to be done:
while True:
gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
if len(gone)>0:
break
这篇关于等待第一个子进程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!