0

我为我的脚本(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()
4

1 回答 1

0

听起来您在原始脚本中使用了线程,这解释了为什么只需按Ctrl+就无法破坏原始脚本C。在这种情况下,您可能希望在脚本中添加一个 KeyboardInterrupt 异常,如下所示:

from time import sleep
def interrupt_this()
    try:
         while True:
             sleep(0.02)
    except KeyboardInterrupt as ex:
         # handle all exit procedures and data cleaning
         print("[*] Handling all exit procedures...")

在此之后,您应该能够自动重新启动您的相关过程(即使从脚本本身,无需任何外部脚本)。无论如何,如果没有看到相关的脚本,这有点难以知道,所以如果你分享一些,也许我可以提供更多帮助。

于 2016-10-16T16:02:05.163 回答