我目前正在并行运行一些子流程(多个子流程),{p1,p2,p3,p4}。
我想等(),直到其中任何一个结束。
我目前正在进行一段时间的轮询,这可能是非常低效的
proc = [p1, p2, p3, p4]
while True:
for p in proc:
if p.poll() != None:
#Do whatever
我想知道,有没有一种方法可以等待最快完成的子流程,而不是忙于等待所有子流程的轮询?
只要您不在Windows上,就可以使用os.wait()
。它被设计为等待第一个子进程退出。
然而,隐藏的副作用是丢失进程的退出代码(现在将假定为0)。可以自己设置,但有点麻烦。
proc = [p1, p2, p3, p4]
pid, status = os.wait()
for p in proc:
if p.pid == pid:
# We need to set the process's exit status now, or we
# won't be able to retrieve it later and it will be
# assumed to be 0.
# This is a kind of hacky solution, but this function has existed
# ever since subprocess was first included in the stdlib and is
# still there in 3.10+, so it *should* be pretty stable.
p._handle_exitstatus(status)
#Do whatever
注意:这一切在python 3 上都同样有效