Wiki » Python专题 » Python打包 »
Nuitka¶
- 安装 nuitka 相关依赖
- 打包
nuitka --standalone --onefile --include-data-files=lib/*=lib/ --output-dir=build test.py
nuitka --standalone --onefile --include-data-files=lib1/*=lib1/ --include-data-files=lib2/*=lib2/ --output-dir=build test.py
注:如果报错:
Nuitka-Options: Used command line options: --standalone --onefile --include-data-files=lib/*=lib/ --output-dir=build test.py
FATAL: Error, standalone mode on Linux requires 'patchelf' to be installed. Use 'apt/dnf/yum install patchelf' first.
apt install patchelf
- 添加额外包示例
nuitka --standalone --onefile --output-dir=build test_oss.py
nuitka --follow-imports --include-package=rknnlite --include-package=ruamel --include-package=psutil --standalone --onefile --include-data-files=/usr/local/lib/python3.8/dist-packages/aliyunsdkcore/data/*=aliyunsdkcore/data/ --include-data-files=/usr/local/lib/python3.8/dist-packages/rknnlite/config/*=rknnlite/config/ --output-dir=build test_oss.py
nuitka --standalone --onefile --nofollow-import-to=cv2,numpy,rknnlite,PIL,configparser,zmq,turbojpeg,aiohttp,oss2,asyncio,requests --include-package=ntpath,_contextvars,_ctypes,urllib.request,http.cookies --output-dir=build test_oss.py
其它:
.\venv\Scripts\python.exe -m nuitka --standalone --onefile --windows-icon-from-ico=1.ico --windows-console-mode=disable --output-dir=build --output-filename="TESTv1.0.exe" --remove-output --lto=yes --jobs=8 --show-progress --follow-imports --python-flag=no_site --python-flag=no_warnings --windows-company-name="ys" --windows-product-name="TEST" --windows-file-version=1.0.0.0 --windows-product-version=1.0.0.0 --include-module=uuid --enable-plugin=pyside6 test.py
- 报错
1. 报错:
nuitka --standalone --onefile --include-data-files=lib/*=lib/ --output-dir=build test_cv.py
Nuitka-Options: Used command line options: --standalone --onefile --include-data-files=lib/*=lib/ --output-dir=build test_cv.py
Nuitka: Starting Python compilation with Nuitka '2.5.9' on Python '3.8' commercial grade 'not installed'.
FATAL: anti-bloat: Error, failed to evaluate expression 'repr(get_variable("cv2_extra_sub_modules"))' in this context, exception was 'SyntaxError('invalid syntax', ('<unknown>', 1, 6, 'LIBGL: Initialising gl4es'))'.
Nuitka-Reports: Compilation crash report written to file 'nuitka-crash-report.xml'.
解决:删除gl4es相关的包
apt remove libgl4es-dev
apt remove libgl4es
- 示例
# 编译成so(不加--lto=no生成的so会更小)
nuitka --module test.py --output-dir=. --lto=no
# 编译成bin(不加--lto=no可能报错)
nuitka test.py --lto=no
# 注:
# LTO 是编译器的一种优化技术,会在链接阶段对所有代码做全局优化
# 启用 LTO 时,编译器会生成特殊的中间文件,链接器(ld)会再次调用编译器来做优化和链接
# 兼容性问题:LTO 需要编译器和链接器的紧密配合,不同版本的 gcc/ld、不同的系统环境,可能会有 bug 或不兼容
# 资源消耗大:LTO 会消耗更多内存和 CPU,容易触发链接器的 bug,尤其是在资源有限或老版本工具链下
# Nuitka 生成的代码复杂:Nuitka 会生成大量 C 代码,LTO 处理这些代码时更容易暴露工具链的缺陷
# GCC 9 的已知问题:你用的是 gcc 9,这一版本的 LTO 在某些场景下有已知的崩溃 bug,尤其是链接大型项目或生成可执行文件时
- 参考
https://www.cnblogs.com/xuguangzong/p/16016421.html
https://baijiahao.baidu.com/s?id=1777902041805714667&wfr=spider&for=pc
https://zhuanlan.zhihu.com/p/689115995