如何在python中使用父进程重新启动失败的进程 [英] How to restart failed process with parent process in python

查看:69
本文介绍了如何在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中使用父进程重新启动失败的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆