【发布时间】:2020-06-19 10:10:12
【问题描述】:
我有一个subprocess' 进程列表。我不与他们交流,只是等待。
我想等待第一个过程完成(此解决方案有效):
import subprocess
a = subprocess.Popen(['...'])
b = subprocess.Popen(['...'])
# wait for the first process to finish
while True:
over = False
for child in {a, b}:
try:
rst = child.wait(timeout=5)
except subprocess.TimeoutExpired:
continue # this subprocess is still running
if rst is not None: # subprocess is no more running
over = True
break # If either subprocess exits, so do we.
if over:
break
我不想使用 os.wait(),因为它可能会从另一个 subprocess 返回,而不是我正在等待的列表的一部分。
一个漂亮而优雅的解决方案可能是使用epoll 或选择并且没有任何循环。
【问题讨论】:
-
为什么不使用
.communicate? -
我认为您的解决方案非常优雅。您能否让进程在完成后(并且仅在完成后)向 stdout 或 stderr 写入内容?
-
还有一个问题——你会考虑使用类似pypi.org/project/psutil的东西吗?
-
子进程不写入 stdout 或 stderr ,我真的不想和他们交流。我不知道 psutil ,我会看看,或者你能用这个 lib 提出一个解决方案吗?谢谢
-
@raphaelauv - 请参阅下面的答案。显然,它们为这个用例提供了一个特定的功能。
标签: python subprocess wait