【问题标题】:How to restart failed process with parent process in python如何在python中使用父进程重新启动失败的进程
【发布时间】:2021-02-17 18:34:20
【问题描述】:

代码:

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。

我知道,上面的代码不是一个正确的实现,但是我用谷歌搜索没有找到合适的解决方案。

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

【问题讨论】:

  • 我会为每个处理轮询状态并在失败时重新启动新的subprocess.Popen() 的进程编写一个包装类。
  • @AKX 是否有代码?
  • SO 不是代码编写服务,您应该可以自己编写这样的类。一般来说,“如果可能的话,用代码”意味着一次咨询演出,但因为这只花了 3 分钟......
  • @AKX 我是这项技术的新手,正在努力学习。我用谷歌搜索但没有找到合适或合适的解决方案,那是我的要求。所以我在 SO 中发帖寻求帮助。

标签: python-3.x subprocess exe


【解决方案1】:

我的评论是这样的:

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() 终止进程)。

【讨论】:

  • 上面的 sol 不起作用,上面的代码为所有 .exe 打印“正在启动”和“失败”,包括成功和失败的进程。
  • Starting C:\Users\XYZ\PycharmProjects\Task1\dist\multiof1.exe Failed: C:\Users\XYZ\PycharmProjects\Task1\dist\multiof1.exe -- 输出
  • 糟糕——修复了这个错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多