首页 > 解决方案 > python程序崩溃后如何重新启动

问题描述

我有一个 python 脚本,它启动一个程序并通过它自动化,不断处理新数据并保存到预设目录。
永久运行 Python 脚本、在发生错误时记录错误并在崩溃时重新启动的推荐方法是什么?
到目前为止,我遇到了os.execv并有这个开始:

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

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

标签: pythonpython-3.x

解决方案


当 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

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

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

script_starter.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")

推荐阅读