我为我的脚本(Python3)创建了一个看门狗计时器,它允许我在出现任何错误时停止执行(下面的代码中没有显示)。但是,我希望能够只使用Python(没有外部脚本)自动重新启动脚本。代码需要跨平台兼容。在
我已经尝试过subprocess和execv(os.execv(sys.executable, ['python'] + sys.argv)
),但是我在Windows上看到了非常奇怪的功能。我打开命令行,运行脚本(“pythonmyscript.py"). 脚本停止但不退出(通过任务管理器验证),除非我按两次enter键,否则它不会自行重新启动。我想让它自动工作。在
有什么建议吗?谢谢你的帮助!在
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()
听起来像是在原始脚本中使用线程,这解释了为什么只需按Ctrl+C就不能破坏原始脚本。在这种情况下,您可能需要将键盘中断异常添加到脚本中,如下所示:
在此之后,您应该能够自动重新启动相关过程(即使是在脚本本身内部,而不需要任何外部脚本)。不管怎样,没有看到相关的脚本是有点难知道的,所以如果你分享一些,也许我能帮上更多的忙。在
相关问题 更多 >
编程相关推荐