Python子进程等待任何一个先完成的子进程

4
我目前正在并行运行一些子进程(多个子进程),{p1,p2,p3,p4}。
我想等待(),直到其中任何一个完成。
我目前正在轮询while循环,这可能非常低效。
proc = [p1, p2, p3, p4]
while True:
  for p in proc:
    if p.poll() != None:
      #Do whatever

我在想,是否有一种方式可以等待最快完成的子进程而不是通过轮询所有子进程进行忙等待?

1个回答

1
只要你不使用Windows,你就可以使用os.wait()来实现这个功能。它专门等待第一个子进程退出。
然而,一个隐藏的副作用是你会失去进程的退出码(现在假定为0)。虽然你可以自己设置,但这有点hacky。
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 中同样适用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接