从Python setuptools创建可启动的GUI脚本(没有控制台窗口!)

2024-06-09 06:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前为基于Python的GUI添加可执行文件的方法是:

setup(
      # ...
      entry_points = {"gui_scripts" : ['frontend = myfrontendmodule.launcher:main']},
      # ...
      )

在Windows上,这将创建“前端.exe“和”前端-脚本.pyw“在Python的scripts文件夹中(使用python2.6)。当我执行EXE文件时,会显示一个控制台窗口,但是PYW文件工作正常,没有显示。在

所以我的问题是:如何让EXE文件在没有控制台窗口的情况下执行程序?该解决方案也可以在Linux上运行(不要建议使用py2exe;)。在


Tags: 文件方法可执行文件mainwindowssetupscriptsgui
2条回答

好吧,我在setuptools源代码中做了一点研究,最终归结为setuptools中的一个bug(很简单)_install.py安装)公司名称:

# On Windows/wininst, add a .py extension and an .exe launcher
if group=='gui_scripts':
    ext, launcher = '-script.pyw', 'gui.exe'
    old = ['.pyw']
    new_header = re.sub('(?i)python.exe','pythonw.exe',header)
else:
    ext, launcher = '-script.py', 'cli.exe'
    old = ['.py','.pyc','.pyo']
    new_header = re.sub('(?i)pythonw.exe','python.exe',header)

if os.path.exists(new_header[2:-1]) or sys.platform!='win32':
    hdr = new_header
else:
    hdr = header

最后一条if语句决定是否pythonw.exe的或python.exe的路径被写进“前端”的shebang中-脚本.pyw". 由于这个shebang是由创建的EXE文件计算的,所以必须不执行else语句。问题是在我的例子中new_header[2:-1]是“C:\ProgramFiles(x86)\Python26\pythonw.exe“(加上引号!),所以os.path.exists说它不存在是因为引号。在

我将尝试让setuptools开发人员纠正这个问题。剩下的问题将是绝对的pythonw.exe路径。如果我创建一个Windows安装程序/MSI安装程序,shebang将包含pythonw.exe路径(“C:\Program Files(x86)\Python26\pythonw.exe),但用户可能已经在“C:\Python26”中安装了Python。在我报告了这个问题之后,我将报告最终的解决方案。在


我在两年前发布了这篇文章,很抱歉我还没有给出我的解决方案。不确定是否有更现代的解决方案(可能是distribute提供了一些东西),但我当时使用的是(复制粘贴):

文件dogsync-frontend-script.pyw

^{pr2}$

文件dogsync-frontend.exe

自动从<python installation>\lib\site-packages\setuptools\gui.exe复制(见下文)。如果我没记错,这个文件将自动执行脚本<name of EXE>-script.py[w]。在

文件setup.py

from setuptools import __file__ as setupToolsFilename

if os.name == "nt":
    # Use a customized (major hack) start script instead of the one that gets automatically created by setuptools
    # when the "gui_scripts" parameter is used. This way, we don't need setuptools installed in order to run DogSync.
    shutil.copy2(os.path.join(os.path.dirname(setupToolsFilename), "gui.exe"),
                 "build-environment/windows-scripts/dogsync-frontend.exe")
    startScripts = dict(scripts = ["build-environment/windows-scripts/dogsync-frontend-script.pyw",
                                   "build-environment/windows-scripts/dogsync-frontend.exe"])
else:
    # For Linux, I don't have a solution to remove the runtime dependency on setuptools (yet)
    startScripts = dict(entry_points = {"gui_scripts" : ['dogsync-frontend = dogsync_frontend.launcher:main']})

setup(<other options>,
      **startScripts)

使用此设置,exe/pyw文件将复制到<python installation>\Scripts(在Windows上),启动dogsync-frontend.exe将在没有控制台的情况下运行pyw脚本。由于setuptools多年没有得到任何更新,所以这个解决方案仍然有效。在

为什么不在Linux上使用.pyw文件,在Windows上使用py2exe?在

相关问题 更多 >