Qt for Python & Nuitka

Nuitka 允许你将你的 Python 应用程序编译成一个独立的可执行文件。除了作为一个提供相当加速的 Python 编译器外,它还具有作为安装程序的副作用。Nuitka 支持 Linux、macOS 和 Windows。

更多详情,请参阅官方文档

准备

通过以下命令使用pip安装Nuitka

pip install nuitka

安装后,nuitka3 二进制文件位于您的虚拟环境的 bin/ 目录中,或者您的 Python 可执行文件所在的位置。此外,您也可以运行:

python3 -m nuitka

达到相同的效果。

冻结应用程序

Nuitka 有许多选项可供使用。要列出所有选项,请运行 nuitka3 -h

要简单地编译一个项目,你可以运行:

nuitka3 <programname>

有两个主要特点:

  • 将其放置在包含库的目录中的选项 (--standalone)

  • 将整个项目(包括共享库)打包成一个可执行文件的选项 (--onefile)

如果您使用这些选项,您需要指定 --plugin-enable=pyside6

运行一个示例

现在,考虑以下脚本,名为 hello.py:

import sys
import random
from PySide6.QtWidgets import (QApplication, QLabel, QPushButton,
                               QVBoxLayout, QWidget)
from PySide6.QtCore import Slot, Qt

class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.hello = ["Hallo Welt", "你好,世界", "Hei maailma",
            "Hola Mundo", "Привет мир"]

        self.button = QPushButton("Click me!")
        self.text = QLabel("Hello World")
        self.text.setAlignment(Qt.AlignCenter)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)

        # Connecting the signal
        self.button.clicked.connect(self.magic)

    @Slot()
    def magic(self):
        self.text.setText(random.choice(self.hello))

if __name__ == "__main__":
    app = QApplication(sys.argv)

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec())

你不需要复制这个脚本。你可以在examples/installer_test/hello.py中找到它。

继续的命令行如下所示:

nuitka3 examples/installer_test/hello.py

这个过程会创建一个可执行的hello.bin和一个你不需要的目录hello.build。你可以直接执行这个二进制文件。

为了创建一个可以在没有任何预先安装的机器上复制的包,请运行:

nuitka3 --standalone --plugin-enable=pyside6 examples/installer_test/hello.py

这将创建一个应用程序 hello.dist/hello,其中包含运行所需的一切。

要运行应用程序,请转到 hello.dist/ 并运行程序:

cd hello.dist
./hello

如果您希望将所有内容捆绑到一个可执行文件中,而不需要旁边的共享库,请使用--onefile选项。首先,您需要安装:

pip install zstandard

用于数据压缩。然后你可以运行:

nuitka3 --onefile --plugin-enable=pyside6 examples/installer_test/hello.py

这个过程需要更长一点时间,但最终你会得到一个可执行文件 hello.bin

./hello.bin