Eastsheng's Wiki

Nuitka 教程:将 Python 脚本编译为可执行文件(exe)

2025-04-09 18:37:28

[toc]

ChatGPT写一个 nuitika 教程:

当然可以!下面是一个面向初学者的 Nuitka 编译 Python 脚本为可执行文件(.exe 或 ELF) 的完整教程,适用于 Windows / Linux / macOS,帮助你从安装到打包走通全流程。


🧊 Nuitka 教程:将 Python 脚本编译为可执行文件(exe)

✅ Nuitka 是什么?

Nuitka 是一个将 Python 代码编译为原生机器代码的编译器,不是简单的打包工具(如 PyInstaller),而是将 Python 转换为高效的 C/C++ 代码,然后编译成原生程序(更快、更安全、更难反编译)。


📦 一、安装 Nuitka

确保你已安装 Python(推荐 Python 3.8–3.11)。

🧱 安装 Nuitka(适用于所有系统):

1
pip install -U nuitka

💡 Windows 用户还需安装 C 编译器:

推荐安装 Visual Studio Build Tools(含 C++ 编译工具)

💡 Linux 用户安装 g++:

1
sudo apt install g++ python3-dev

🧪 二、准备一个简单的 Python 脚本

创建一个文件 hello.py

1
2
3
4
5
def greet(name):
print(f"Hello, {name}!")

if __name__ == '__main__':
greet("World")

⚙️ 三、使用 Nuitka 编译

🚀 基本编译命令(跨平台):

1
nuitka hello.py

生成的可执行文件:

  • Windows: hello.exe
  • Linux/macOS: hello.bin 或无扩展名的可执行文件

🎯 四、常用选项说明(推荐)

1
2
3
4
5
6
7
nuitka hello.py \
--standalone \
--enable-plugin=tk-inter \
--onefile \
--follow-imports \
--output-dir=dist \
--windows-disable-console # 可选:GUI程序时隐藏黑框窗口

🔍 参数解析:

参数 作用
--standalone 打包所有依赖到独立目录
--onefile 生成一个独立 .exe 文件(注意启动较慢)
--follow-imports 包含所有导入模块(推荐)
--enable-plugin=xxx 启用对应插件(如 tkinter, numpy, etc)
--windows-disable-console 对于 GUI 程序不显示命令行窗口
--output-dir=dist 指定输出目录

📁 五、编译输出说明

使用 --standalone 后,输出目录结构:

1
2
3
dist/
hello.exe ← 可执行文件
hello.dist/ ← 所有依赖(Python 解释器、模块等)

使用 --onefile 后,仅输出一个 .exe 文件,但首次运行时会解压到临时目录。


🔐 六、优点与注意事项

优点

  • 编译为原生代码(不是打包 pyc)
  • 更高运行性能(尤其对逻辑密集型)
  • 不易反编译
  • 支持 numpy、tkinter、PyQt 等常见库

⚠️ 注意事项

  • 首次使用 onefile 比较慢(因为解压)
  • 编译时间比 PyInstaller 稍久
  • 有些库可能需要额外插件或参数(如 matplotlib)

🔚 七、示例命令汇总

1
nuitka hello.py --standalone --follow-imports --onefile --output-dir=dist

🔧 八、编译包含依赖的项目(如 Flask、PyQt)

1
2
3
4
5
6
nuitka app.py \
--standalone \
--enable-plugin=pyqt5 \
--include-package=yourmodule \
--follow-imports \
--onefile