[英]Python: Run 2 processes in parallel then wait for all with timeout
Looking for some best practices for the following python3 task:为以下 python3 任务寻找一些最佳实践:
program1
in non-blocking mode以非阻塞模式运行进程program1
program2
in non-blocking mode以非阻塞模式运行进程program2
I reckon I know how to do it for 1 process:我想我知道如何为 1 个过程做到这一点:
import subprocess
p = subprocess.Popen('program1', shell=True)
try:
stdout, stderr = p.communicate(timeout=200)
except subprocess.TimeoutExpired as t:
print(t)
p.kill()
outs, errs = p.communicate()
However I can't expand this approach for 2-processes case, because p.communicate
blocks until program1
ends or timeout exceeds.但是,我无法将这种方法扩展到 2 进程的情况,因为p.communicate
阻塞直到program1
结束或超时。
Also I'd like to know immediately if one of the programs fails.我也想立即知道其中一个程序是否失败。
Python3, OS Linux Python3,操作系统 Linux
UPD I need to implement it wisely, without any busy loops, threads etc UPD我需要明智地实现它,没有任何繁忙的循环、线程等
Process has a join()
method similar to threads. Process 有一个类似于线程的join()
方法。 So, in your case:所以,在你的情况下:
proc_1 = Process(target=my_func_1)
proc_2 = Process(target=my_func_2)
for proc in [proc_1, proc_2]:
proc.start()
# They are doing their thing and when they've completed they will join the
# main process and your main program can resume
for proc in [proc_1, proc_2]:
proc.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.