如何在python中使用父进程重新启动失败的进程

编程入门 行业动态 更新时间:2024-10-09 16:25:51
本文介绍了如何在python中使用父进程重新启动失败的进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

代码:

execs = ['C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\multiof1.exe', 'C:\\Users\\XYZ\\PycharmProjects\\Task2\\dist\\multiof2.exe', 'C:\\Users\\XYZ\\PycharmProjects\\Task3\\dist\\multiof3.exe', 'C:\\Users\\XYZ\\PycharmProjects\\failedprocess\\dist\\multiof4.exe' ] print('Parent Process id : ', os.getpid()) process = [subprocess.Popen(exe) for exe in execs] for proc in process: proc.wait() print('Child Process id : ', proc.pid) if proc.poll() is not None: if proc.returncode == 0: print(proc.pid, 'Exited') elif proc.returncode > 0: print('Failed:', proc.pid)

在上面,.exe的一个子.exe将失败,我需要从父进程重新启动该失败的.exe.

In the above, .exe's one-child .exe will fail and I need to restart that failed .exe from the parent process.

我知道,以上代码不是正确的实现,但我用Google搜索找不到合适的解决方案.

I know, the above code is not a correct implementation but I googled not found a suitable solution.

任何支持都会帮助我了解有关子流程的更多信息.

Any support will help me to learn more about the subprocess.

推荐答案

我的意思是这样的:

import subprocess import time execs = [ "C:\\Users\\XYZ\\PycharmProjects\\Task1\\dist\\multiof1.exe", "C:\\Users\\XYZ\\PycharmProjects\\Task2\\dist\\multiof2.exe", "C:\\Users\\XYZ\\PycharmProjects\\Task3\\dist\\multiof3.exe", "C:\\Users\\XYZ\\PycharmProjects\\failedprocess\\dist\\multiof4.exe", ] class WrappedProcess: def __init__(self, exe): self.exe = exe self.process = None self.success = False def check(self): if self.success: # Nothing to do, we're already successful. return if self.process is None: # No current process, start one. print("Starting", self.exe) self.process = subprocess.Popen(self.exe) return # Only poll on next check if self.process.poll() is None: # Not quit yet. return if self.process.returncode == 0: print("Finished successfully:", self.exe) self.success = True else: print("Failed:", self.exe) # Abandon the process; next check() will retry. self.process = None wrapped_processes = [WrappedProcess(exe) for exe in execs] while True: for proc in wrapped_processes: proc.check() if all(proc.success for proc in wrapped_processes): print("All processes ended successfully") break time.sleep(1)

添加最长时间"也很容易功能(在开始新流程时,存储当前时间;如果过期,请让 check()终止该流程).

It's also easy to add a "max time" feature here (when starting a new process, store the current time; have check() terminate a process if it's overdue).

更多推荐

如何在python中使用父进程重新启动失败的进程

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

发布评论

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

>www.elefans.com

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