2016-10-16 250 views
0

我为我的脚本(Python 3)创建了一个监视程序计时器,它允许我在出现任何问题时停止执行(未在下面的代码中显示)。不过,我希望能够仅使用Python自动重新启动脚本(无需外部脚本)。代码需要跨平台兼容。自我重新启动Python脚本

我已经尝试子流程和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() 

回答

0

听起来像是你在你的原剧本,这也解释了为什么你不能打破你原来的脚本只需按下Ctrl键+ç使用线程。在这种情况下,你可能要一个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...") 

在这之后,你应该能够甚至从脚本本身内自动重新启动有关程序(,无需任何外部脚本)。无论如何,如果没有看到相关的脚本,就很难知道,所以如果你分享一些脚本,也许我会有更多的帮助。

+0

感谢您的回应!我遇到的问题不在于未显示的脚本,而是在发布的代码中。事实证明,当我在Windows上运行脚本的时钟倍增时,它工作正常,但是当我从命令行键入“python myscript.py”时,它不起作用。 Linux中没有当前的问题。 – NJC