我为我的脚本(Python 3)创建了一个看门狗计时器,如果出现任何问题,我可以暂停执行(下面的代码中未显示)。但是,我希望能够仅使用 Python(无外部脚本)自动重新启动脚本。代码需要跨平台兼容。
我已经尝试过 subprocess 和 execv ( os.execv(sys.executable, ['python'] + sys.argv)
),但是我在 Windows 上看到了非常奇怪的功能。我打开命令行,运行脚本(“python myscript.py”)。脚本停止但不退出(通过任务管理器验证),除非我按两次回车,否则它不会自行重启。我希望它自动工作。
有什么建议么?谢谢你的帮助!
import threading
import time
import subprocess
import os
import sys
if __name__ == '__main__':
print("Starting thread list: " + str(threading.enumerate()))
for _ in range(3):
time.sleep(1)
print("Sleeping")
''' Attempt 1 with subprocess.Popen '''
# child = subprocess.Popen(['python',__file__], shell=True)
''' Attempt 2 with os.execv '''
args = sys.argv[:]
args.insert(0, sys.executable)
if sys.platform == 'win32':
args = ['"%s"' % arg for arg in args]
os.execv(sys.executable, args)
sys.exit()