不要等待子进程,而是稍后检查返回码

Don't wait for subprocesses, but check for returncode later on

我正在编写一个 运行 包含多个子进程的脚本。该脚本应该能够 运行 它们全部,然后在循环中检查它们是否已完成。

不开始一个,等它结束,然后开始下一个。

例如:

sp1 = subprocess.Popen(["sleep 60", shell=True)
sp2 = subprocess.Popen(["sleep 10", shell=True)
sp3 = subprocess.Popen(["sleep 80", shell=True)

sp1_done = False
sp2_done = False
sp3_done = False
while not sp1_done and not sp2_done and not sp3_done:
    if sp1.returncode and not sp1_done:
        print("sp1 done")
        sp1_done = True
    if sp2.returncode and not sp2_done:
        print("sp2 done")
        sp2_done = True
    if sp3.returncode and not sp3_done:
        print("sp3 done")
        sp3_done = True

print("all done")

我读到可以使用

访问子进程的错误代码

sp1_data = sp1.communicate()[0] 然后

returncode = sp1.returncode

但是像这样,脚本会等待 sp1 完成。

我如何 运行 多个子流程,而不是等待它们完成,而是检查它们是否完成(例如,通过检查 return 代码)?

您需要为每个启动的子进程使用poll 方法。并检查返回码不是 None:

 while ....  # as written
     sp1.poll()
     sp2.poll()
     sp3.poll()
     if sp1.returncode is not None and not sp1_done:
          .... # as written
     ... # as written