使用pyinstaller重新启动编译后的python脚本



我正在用python+tkinter编程一个小应用程序,显示一个带有一些小部件的窗口。窗口从远程数据源读取数据,在某些情况下,我希望应用程序重新启动(关闭+打开)。它在执行python脚本(源代码)时工作正常,但在编译为exe文件(pyinstaller——onfile——window)时不起作用。

我尝试了两种方法,这两种方法都可以在源代码中完美地工作:

  1. os.execv (sys。sys.argv argv [0])
  2. os.execv (sys。可执行文件,['python'] + sys.argv)

当编译为exe时,应用程序被关闭但永远不会重新启动。我已经将argv的值打印到日志中:

系统。argv[0]=C:Program Files (x86)Grid Positionsgridpositions.exe, sys. exeargv=['C:Program Files (x86)Grid Positionsgridpositions.exe']

应用程序安装在C:Program Files (x86)Grid Positions,具有正确的写入权限,使用innosetup installer制作setup.exe

os.execv(...)方法的调用取决于应用程序是在python解释器中运行还是在pyinstaller中的.exe中运行。

下面是一个处理这个问题的函数(在Windows上测试,但没有在临时文件夹中解压缩.exe):

import sys, os
def restart_main():
# Restart the application...
executable = sys.executable
executable_filename = os.path.split(executable)[1]
if executable_filename.lower().startswith('python'):
# application is running within a python interpreter
python = executable
os.execv(python, [python, ] + sys.argv)
pass
else:
# application is running as a standalone executable
os.execv(executable, sys.argv)
pass
pass

最新更新