如果 Python 程序被终止,则自动重新启动它

Automatically restart a Python program if it's killed

我 运行 一个 Python Discord 机器人。我导入了一些模块并有一些事件。时不时地,脚本似乎由于某种未知原因而被杀死。也许是因为 error/exception 或某些连接问题?我不是 Python 专家,但我设法让我的机器人工作得很好,我只是不完全理解它是如何在引擎盖下工作的(因为程序除了等待事件之外什么都不做)。无论哪种方式,我都希望它在停止后自动重新启动。

我使用 Windows 10,如果我不想要 window,只需双击它或通过 pythonw.exe 启动我的程序。验证我的程序是否仍在 运行ning 的最佳方法是什么(它不必是即时的,验证可以每 X 分钟完成一次)?我想过使用批处理文件或其他 Python 脚本,但我不知道该怎么做。

感谢您的帮助。

对于你所说的问题,我更喜欢使用 python subprocess call to rerun python script or use try blocks。 这可能对你有帮助。 检查此示例尝试块代码:

try:
  import xyz # consider it is not exist or any error code
except:
  pass # go to next line of code to execute

您可以编写另一个 python code (B) 来使用 subprocess 中的 Popen 来调用您原来的 python code (A)。在 python code (B) 中,要求程序为您的 python code (A) wait。如果 'A'error code 退出,recall 它来自 B

我提供了一个例子python_code_B.py

import subprocess

filename = 'my_python_code_A.py'
while True:
    """However, you should be careful with the '.wait()'"""
    p = subprocess.Popen('python '+filename, shell=True).wait()

    """#if your there is an error from running 'my_python_code_A.py', 
    the while loop will be repeated, 
    otherwise the program will break from the loop"""
    if p != 0:
        continue
    else:
        break

这通常适用于 Unix / Windows 系统。在 Win7/10 上测试了最新的代码更新。

此外,请 运行 python_code_B.py 来自 'real terminal' 这意味着 运行 从命令提示符或终端,而不是空闲状态。