等待第一个子进程完成

编程入门 行业动态 更新时间:2024-10-15 12:35:13
本文介绍了等待第一个子进程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个 subprocess 进程列表.我不与他们沟通,只是等待.

I have a list of subprocess' processes. I do not communicate with them and just wait.

我想等待第一个进程完成(此解决方案有效):

I want to wait for the first process to finish (this solution works):

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 返回,而不是我正在等待的列表的一部分.

I don't want use os.wait(), cause it could return from another subprocess not part of the list I'm waiting for.

一个好的和优雅的解决方案可能是使用 epoll 或 select 并且没有任何循环.

A nice and elegant solution would probably be with an epoll or select and without any loop.

推荐答案

这是一个使用 psutil 的解决方案 - 它正是针对这个用例:

Here's a solution using psutil - which is aimed exactly at this use-case:

import subprocess import psutil a = subprocess.Popen(['/bin/sleep', "2"]) b = subprocess.Popen(['/bin/sleep', "4"]) procs_list = [psutil.Process(a.pid), psutil.Process(b.pid)] def on_terminate(proc): print("process {} terminated".format(proc)) # waits for multiple processes to terminate gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)

或者,如果您希望循环等待其中一个进程完成:

Or, if you'd like to have a loop waiting for one of the process to be done:

while True: gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate) if len(gone)>0: break

更多推荐

等待第一个子进程完成

本文发布于:2023-11-04 18:14:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1558661.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:个子   进程

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!