崩溃后如何重新启动python程序

新手上路,请多包涵

我有一个 python 脚本,它启动一个程序并自动执行它,不断处理新数据并保存到预设目录。

永久运行 Python 脚本、在错误发生时记录错误并在崩溃时重新启动的推荐方法是什么?

到目前为止,我遇到了 os.execv 并开始:

 import sys
import os

def pyexcept(t, v, tb):
   import traceback
## restarts the script
os.execv( sys.executable, '')

但是我经常在试图弄清楚下一步时陷入困境,有人可以解释我可以采取的下一步,ty!

原文由 Shone118 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 829
1 个回答

当 python 脚本崩溃时, 程序 不再运行,因此脚本无法执行更多的代码行。

您有 2 个选择:

  1. 确保你的 python 脚本不会崩溃,这是非常推荐的。您可以通过处理程序抛出的异常来做到这一点。

选项1

我假设您是 python 的新手,所以这里是一个处理异常的 python 脚本示例,它再次调用相同的函数。

 from time import sleep

def run_forever():
    try:
        # Create infinite loop to simulate whatever is running
        # in your program
        while True:
            print("Hello!")
            sleep(10)

            # Simulate an exception which would crash your program
            # if you don't handle it!
            raise Exception("Error simulated!")
    except Exception:
        print("Something crashed your program. Let's restart it")
        run_forever() # Careful.. recursive behavior
        # Recommended to do this instead
        handle_exception()

def handle_exception():
    # code here
    pass

run_forever()

  1. 如果你想重新启动 python 脚本,你将需要另一个 python 脚本 (假设你想用 python 执行此操作) 来检查进程是否仍然存在,如果没有,则使用 python 再次运行它。

选项 2

这是通过命令 python test.py 启动另一个名为 “test.py” 的 python 脚本的脚本。确保你有正确的文件路径,如果你把脚本放在同一个文件夹中,你通常不需要完整路径,只需要脚本名称。

值得注意的是,确保命令“ python ”被你的系统识别,在某些情况下它可以被 “python3” 识别

脚本启动器.py

 from subprocess import run
from time import sleep

# Path and name to the script you are trying to start
file_path = "test.py"

restart_timer = 2
def start_script():
    try:
        # Make sure 'python' command is available
        run("python "+file_path, check=True)
    except:
        # Script crashed, lets restart it!
        handle_crash()

def handle_crash():
    sleep(restart_timer)  # Restarts the script after 2 seconds
    start_script()

start_script()

如果您对我用于测试文件的代码感兴趣:“test.py”,我将其发布在这里。

测试.py

 from time import sleep
while True:
    sleep(1)
    print("Hello")
    raise Exception("Hello")

原文由 Velocity-plus 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题