Contents

[TOC]

Nuitka

其他方案筛选对比

对比维度 PyInstaller Nuitka PyOxidizer
核心原理 打包工具,将Python代码及依赖封装为独立可执行文件 编译器,将Python代码编译为C/C++后生成二进制文件 基于Rust开发,静态链接Python解释器及依赖生成独立可执行文件
输出形式 单文件夹或单文件(含依赖) 单文件二进制(体积更小) 单文件二进制(完全独立)
性能优化 无编译优化,依赖解释器执行 编译优化,执行速度接近原生代码 静态链接优化,启动速度快
兼容性 跨平台(Windows/Linux/macOS) 跨平台,支持Python 2.x/3.x 跨平台,支持多架构构建
安全性 依赖项可见,易逆向 编译为C代码,安全性较高 静态链接,安全性最高
维护成本 配置简单,适合快速部署 编译时间长,需处理C依赖 需Rust知识,社区支持较弱
适用场景 简单脚本、GUI应用、快速原型验证 计算密集型任务、AI模型推理、性能关键场景 需要静态链接、高安全性的嵌入式场景

Nuitka 使用

  • 代码
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
├── main.py
├── main_window.py
├── resources
│   └── config.yaml
├── run.sh
└── utils
    ├── config.py
    ├── gs_trtp_player.py
    ├── logger.py
    └── stream_controller.py
  • 打包脚本
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
nuitka  --standalone --follow-imports \
        --include-module=gi \
        --include-module=cv2 \
        --include-module=gi._gi \
        --include-module=gi.repository \
        --include-package=gi.repository \
        --include-module=numpy \
        --include-module=numpy.linalg \
        --static-libpython=no \
        --enable-plugin=numpy \
        --enable-plugin=pyqt5 \
        --enable-plugin=gi \
        --include-package=utils \
        --include-data-file=./resources/config.yaml=./resources/config.yaml \
        --verbose \
        main.py

Standalone 或 One-file 模式那样创建一个独立的运行环境

–follow-imports 会递归地编译整个程序
–follow-imports –include-plugin-directory=plugin_dir 如果有一个带有动态加载文件的源目录,即通过 PYTHONPATH 正常导入语句后无法找到的目录(这将是推荐的方式),可以要求一个特定的目录也应包括在可执行文件中。如果你不做任何动态导入,只需在编译时设置你的 PYTHONPATH 就可以了,只有在你进行 Nuitka 无法预测的 __import__() 调用时,才使用 --include-plugin-directory
–module python -m nuitka --module some_module.py : 编译扩展模块some_module.so
–standalone 会递归地编译整个程序,如果排除模块需要使用 --nofollow-import-to
–include-data-file=/etc/*.txt=etc/ 其中 source 是一个文件系统路径,但 target 必须指定为相对路径。
–include-data-dir=/path/to/images=images
–include-package-data
–onefile
–low-memory 要求 Nuitka 使用更少的内存
--lto=yes--lto=no
–enable-shared

问题:

1
FATAL: Error, data files cannot be included in accelerated mode unless using commercial plugins '--embed-*' options. Not done for 'examples/music/finish/1.wav'.

–follow-imports

–enable-plugin

–enable-plugin=numpy –enable-plugin=tensorflow

优先使用插件 会优化性能

–include-package

会扩大包体积

–include-module

解决动态导入问题?