我有一个列表 subprocess
' 过程。我不与他们沟通,只是等待。
我想等待第一个过程完成(此解决方案有效):
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
返回不是我正在等待的列表的一部分。一个好的和优雅的解决方案可能是使用
epoll
或选择并且没有任何循环。
最佳答案
这是使用 psutil 的解决方案 - 正是针对此用例:
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)
或者,如果您希望循环等待其中一个进程完成:while True:
gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
if len(gone)>0:
break
关于python - 等待第一个子进程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62467974/