wait process until all subprocess finish?(等待进程直到所有子进程完成?)
问题描述
我有一个创建两个或多个子进程的主进程,我希望主进程等到所有子进程完成操作并退出?
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
...
推荐答案
一个 Popen
对象有一个 .wait()
方法正是为此定义的:等待给定子进程的完成(此外,对于重新调整其退出状态).
A Popen
object has a .wait()
method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).
如果你使用这种方法,你可以防止进程僵尸停留太久.
If you use this method, you'll prevent that the process zombies are lying around for too long.
(或者,您可以使用 subprocess.call()
或 subprocess.check_call()
用于调用和等待.如果您不需要进程的 IO,那可能就足够了.但这可能不是一个选项,因为您的 if 两个子进程似乎应该在其中运行并行,他们不会使用 (check_
)call()
.)
(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()
.)
如果你有几个子流程要等待,你可以这样做
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.
这篇关于等待进程直到所有子进程完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:等待进程直到所有子进程完成?


- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01