【问题标题】:How to make a Python script run without it opening the console window?如何在不打开控制台窗口的情况下运行 Python 脚本?
【发布时间】:2015-09-25 03:14:59
【问题描述】:

我想双击我的 Python 脚本(它使用 Tkinter GUI),我只想打开 Tkinter 窗口,而不是控制台窗口。

为此,我将扩展名从 .py 更改为 .pyw,这在 Windows 上似乎可以正常工作,但是当我在 Linux 机器上双击我的 .pyw 文件时,它不起作用。它只是冻结了,我不得不重新启动我的系统。

请建议一个独立于平台的解决方案,它可以帮助我在不打开终端/命令提示符的情况下运行 Python 脚本。

【问题讨论】:

  • 这在 Windows 上工作的原因是它运行一个不同的可执行文件,称为pythonw.exe。恐怕我不知道 Linux 上的等价物是什么。

标签: python tkinter


【解决方案1】:

您可以使用pyinstaller 为您想要的不同平台创建可执行文件。

例如,

pyinstaller 命令的语法是:

pyinstaller [options] script [script ...] | specfile

在最简单的情况下,将当前目录设置为你的程序 myscript.py 的位置并执行:

pyinstaller myscript.py

PyInstaller 分析 myscript.py 并:

Writes myscript.spec in the same folder as the script.
Creates a folder build in the same folder as the script if it does not exist.
Writes some log files and working files in the build folder.
Creates a folder dist in the same folder as the script if it does not exist.
Writes the myscript executable folder in the dist folder.

在 dist 文件夹中,您可以找到分发给用户的捆绑应用程序。

通常你在命令行上命名一个脚本。如果您命名更多,则所有内容都会被分析并包含在输出中。但是,第一个名为的脚本提供了规范文件和可执行文件夹或文件的名称。它的代码在运行时首先执行。

对于某些用途,您可以编辑 myscript.spec 的内容(在使用规范文件中描述)。完成此操作后,将规范文件命名为 PyInstaller 而不是脚本:

pyinstaller myscript.spec

您可以给出脚本或规范文件的路径,例如

pyinstaller options... ~/myproject/source/myscript.py

或者,在 Windows 上,

pyinstaller "C:\Documents and Settings\project\myscript.spec"

pyinstaller

【讨论】:

    【解决方案2】:

    自从我在 linux 上尝试以来已经有一段时间了,但我相信它应该相当简单,首先你需要在脚本的顶部放置一个 shebang 以便你的 shell 知道要使用哪个可执行文件:

    #!/usr/bin/python
    

    或者如果您想要特定版本,您可以将其扩展为:

    #!/usr/bin/python3.2
    

    使用您想要的任何版本(仅适用于前 2 位数字)

    然后你需要将它标记为可执行:

    chmod 711 myfile.py
    

    有关这方面的更多信息,请参阅page

    然后当你双击它时,在 rpi(我上次使用 linux)上它会询问你是要执行它,还是在终端中执行它。

    如果你选择在没有终端的情况下执行它,你应该只看到 tkinter GUI

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多