繁体   English   中英

如果它被杀死,自动重启Python程序

[英]Automatically restart a Python program if it's killed

我运行Python Discord bot。 我导入一些模块并有一些事件。 偶尔,脚本似乎因某种未知原因而被杀死。 可能是因为错误/异常或某些连接问题可能? 我不是Python专家,但我设法使我的机器人工作得很好,我只是不完全理解它是如何工作的(因为程序除了等待事件之外什么都不做)。 无论哪种方式,我希望它在停止后自动重启。

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

谢谢你的帮助。

您可以使用subprocess Popen编写另一个python code (B)来调用原始python code (A) python code (B) ,让程序wait你的python code (A) 如果'A'退出并显示error coderecallB

我提供了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 ,这意味着从命令提示符或终端运行,而不是在IDLE中运行。

对于你说的问题,我更喜欢使用python 子进程调用来重新运行python脚本或使用try块 这可能对您有所帮助。 检查此示例尝试块代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM