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