Python 等待进程直到所有子进程完成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15107714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:20:47  来源:igfitidea点击:

wait process until all subprocess finish?

pythonsubprocessipc

提问by Nikhil Rupanawar

I have a main process which creates two or more sub processes, I want main process to wait until all sub processes finish their operations and exits?

我有一个创建两个或多个子进程的主进程,我希望主进程等到所有子进程完成其操作并退出?

 # main_script.py

 p1 = subprocess.Popen(['python script1.py']) 
 p2 = subprocess.Popen(['python script2.py'])
 ... 
 #wait main process until both p1, p2 finish
 ...

采纳答案by glglgl

A Popenobject has a .wait()method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

一个Popen对象有一个.wait()为此精确定义的方法:等待给定子进程的完成(此外,重新调整其退出状态)。

If you use this method, you'll prevent that the process zombies are lying around for too long.

如果您使用此方法,您将防止进程僵尸停留太久。

(Alternatively, you can use subprocess.call()or subprocess.check_call()for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

(或者,您可以使用subprocess.call()subprocess.check_call()进行调用和等待。如果您不需要进程的 IO,那可能就足够了。但这可能不是一个选项,因为您的 if 两个子进程似乎应该并行运行,他们不会与 ( check_) call()。)

If you have several subprocesses to wait for, you can do

如果你有几个子进程要等待,你可以做

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

一旦所有子流程完成,它就会返回。然后,您有一个返回代码列表,您可以对其进行评估。

回答by Gjordis

subprocess.call

Automatically waits , you can also use:

自动等待,你也可以使用:

p1.wait()