日期:2025-12-05
标签:Python、PyInstaller、Nuitka、打包、部署、exe


1. 为什么写这篇文章

.py 交给用户前,永远不知道对方电脑里有没有 Python、pip、VC++ 运行库,甚至网。
一款趁手的打包工具,能把所有依赖“一锅端”,一键生成 .exe / .app / .elf,让程序“双击即跑”。
但工具一多就犯难:PyInstaller、cx_Freeze、py2exe、Nuitka、PyOxidizer……到底选谁?
本文用一张决策图 + 全流程示例,带你 10 分钟搞定“Python 打包方式选择”。


2. 5 大主流工具速览表

维度 PyInstaller cx_Freeze py2exe Nuitka PyOxidizer
打包机制 捆绑解释器 捆绑解释器 捆绑解释器 真·编译 Rust 嵌入
跨平台 ✅ Win/Mac/Linux ✅ 三平台 ❌ 仅 Win ✅ 三平台 ✅ 三平台
单文件 --onefile --onefile
启动速度 慢(需解压) 中等 中等
体积 30-50 MB 40-60 MB 20-40 MB 10-20 MB 15-30 MB
反编译难度 极低 极低 极低 (C 二进制)
学习成本 1 行命令 1 个 setup.py 1 个 setup.py 2 行命令 需写 TOML
维护状态 活跃 活跃 停滞 活跃 活跃

一句话记忆:
要快要小要安全,直接上 Nuitka;只求能跑,PyInstaller 足够。


3. 原理图解(记住两张图,选型不纠结)

3.1 捆绑型(PyInstaller / cx_Freeze / py2exe)

┌────────────── 生成的 exe ┐
│  Bootloader                │
│  ├─ python3x.dll           │
│  ├─ 标准库 .pyc            │
│  ├─ 三方库 .pyc            │
│  ├─ 你的代码 .pyc  ← 可被 uncompyle6 反编译 │
│  └─ 资源文件(图标、ui)    │
└────────────────────────────┘
运行时先解压到临时目录,再启动解释器,所以慢、大、易破解。

3.2 编译型(Nuitka)

.py → 语法树 → C 代码 → Clang/GCC → 本地机器码
真正的 Ahead-Of-Time 编译,.pyc 不存在,反编译≈逆向 C。

体积天生小、启动原地起飞,还能配合 strip/upx 进一步压缩。


4. 实战:同一段代码 3 种打包对比

示例程序:hello.py(tkinter 弹窗)

import tkinter as tk
root = tk.Tk()
root.title("Demo")
tk.Label(root, text="Hello Python!").pack()
root.mainloop()
工具 命令 结果大小 首次启动 反编译难度
PyInstaller pyinstaller --onefile --windowed hello.py 35.2 MB 2.1 s 一键 uncompyle6
Nuitka python -m nuitka --standalone --onefile --windows-disable-console hello.py 11.7 MB 0.4 s IDA 逆向
cx_Freeze python setup.py build(setup.py 略) 42.6 MB 1.8 s 同 PyInstaller

注:环境 Win10 x64 / Python 3.11 / UPX 未开。


5. 场景决策树(直接收藏)

我需要打包 Python 程序
├─ 仅内部用,越快越好 → PyInstaller --onefile
├─ 要发客户,怕源码泄露 → Nuitka --onefile
├─ 嵌入式/Rust 生态 → PyOxidizer
├─ 老项目只跑 WinXP → py2exe
└─ 要打包成系统服务 → cx_Freeze(可自定义 Windows Service)

6. 常见问题 FAQ

Q1 用户电脑报“Virus”?
A: 单文件模式容易被误杀。

  • PyInstaller:让朋友加白名单,或用 --onedir 目录版。
  • Nuitka:编译型误报率显著降低,可再签数字证书。

Q2 图标、manifest、UAC 怎么加?
PyInstaller:

pyinstaller --onefile --icon=app.ico --manifest uac.xml app.py

Nuitka:

--windows-icon=app.ico --windows-uac-admin

Q3 还有更小的方案吗?
A:

  1. 用 Nuitka + strip + upx --best 可再减 20%。
  2. 静态链接 musl(Linux)或 msvcrt(Windows)能到 6-8 MB,但需自行编译 Python。

7. 结论(省流版)

  • 原型/开源/内部 → PyInstaller,一条命令完事。
  • 商业/付费/想加密 → Nuitka,体积最小、速度最快、反编译最难。
  • 折腾党/ Rust 粉 → PyOxidizer,TOML 写到怀疑人生,但可控度 Max。

把这篇收藏,下次不用再翻 20 页文档,3 秒选出最适合你的 Python 打包方案!


8. 附录:极速复制粘贴命令

# 1. 安装
pip install -U pyinstaller nuitka cx_Freeze

# 2. PyInstaller 单文件
pyinstaller --onefile --windowed --icon=app.ico main.py

# 3. Nuitka 单文件(Windows)
python -m nuitka --standalone --onefile --windows-disable-console --windows-icon=app.ico main.py

# 4. Nuitka 单文件(Linux/Mac)
python -m nuitka --standalone --onefile main.py

Happy Shipping!祝你的程序一次打包,天下畅跑!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐