【问题标题】:Python Subprocess Wait for any subprocess which finishes first [duplicate]Python子进程等待任何首先完成的子进程[重复]
【发布时间】:2013-07-07 02:18:37
【问题描述】:

我目前正在并行运行一些子进程(多个子进程),{p1, p2, p3, p4}。

我想 wait() 直到其中任何一个完成。

我目前正在一个 while 循环中进行轮询,这可能效率很低

proc = [p1, p2, p3, p4]
while True:
  for p in proc:
    if p.poll() != None:
      #Do whatever

我想知道,有没有办法等待最快完成的子进程,而不是忙于等待轮询所有子进程?

【问题讨论】:

    标签: python python-2.7 subprocess wait polling


    【解决方案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 上同样适用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-13
      • 1970-01-01
      • 2013-09-24
      相关资源
      最近更新 更多