当python脚本崩溃时,程序不再运行,因此脚本无法执行更多行代码。
你有两个选择:
- 确保您的 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()
- 如果你想重新启动 python 脚本,你需要另一个 python 脚本(假设你想用 python 来做这个)来检查进程是否还活着,如果没有,然后再次运行它蟒蛇。
选项 2
这是通过命令python test.py 启动另一个名为'test.py' 的python 脚本的脚本。
确保你有正确的文件路径,如果你把脚本放在同一个文件夹中,你通常不需要完整路径,只需要脚本名称。
值得注意的是,确保您的系统能够识别命令“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',我把它贴在这里。
test.py
from time import sleep
while True:
sleep(1)
print("Hello")
raise Exception("Hello")