优化exe文件体积

This commit is contained in:
2026-08-16 12:26:29 +08:00
parent a06b90bf77
commit 2e893099ea
3 changed files with 305 additions and 1 deletions
+5
View File
@@ -4,3 +4,8 @@
.vscode .vscode
PyApp/venv PyApp/venv
PyApp/__pycache__ PyApp/__pycache__
PyApp/build
PyApp/dist
PyApp/pyicache
PyApp/upx
*.spec.bak
+179
View File
@@ -0,0 +1,179 @@
# SikoraDaqReader 上位机 exe 打包说明
本文档记录将 [PyApp/main.py](main.py) 打包为单文件 exe 的完整步骤、体积优化策略与注意事项。
---
## 1. 环境与依赖
### 1.1 Python 环境
- Python 3.11(64 位)
- 依赖包(见 [requirements.txt](requirements.txt)):
```
PyQt5>=5.15
pyqtgraph>=0.12
pyserial>=3.5
```
- 打包工具:`pyinstaller>=6.0`(已随环境安装)
安装依赖:
```powershell
pip install -r PyApp/requirements.txt
pip install pyinstaller
```
### 1.2 UPX 压缩工具
- 版本:UPX 4.2.4(win64)
- 位置:[PyApp/upx/upx-4.2.4-win64/upx.exe](upx/upx-4.2.4-win64/upx.exe)
- 作用:压缩 exe 内嵌的 DLL / PYD,显著减小体积
- 若缺失,可重新下载:
```powershell
$url = "https://github.com/upx/upx/releases/download/v4.2.4/upx-4.2.4-win64.zip"
Invoke-WebRequest -Uri $url -OutFile PyApp\upx.zip -UseBasicParsing
Expand-Archive -Path PyApp\upx.zip -DestinationPath PyApp\upx -Force
Remove-Item PyApp\upx.zip
```
---
## 2. 目录结构
```
PyApp/
├── main.py # 上位机源码
├── requirements.txt # Python 依赖
├── main.spec # PyInstaller 打包配置(核心)
├── upx/ # UPX 压缩工具(已下载, 已 gitignore)
│ └── upx-4.2.4-win64/upx.exe
├── pyicache/ # PyInstaller 缓存(已 gitignore)
├── build/ # 打包中间产物(已 gitignore)
└── dist/ # 打包输出(已 gitignore)
└── SikoraDaqReader.exe # 最终单文件 exe
```
打包产物(`build/`、`dist/`、`pyicache/`、`upx/`)已在 [.gitignore](../.gitignore) 中忽略,不会提交到仓库。
---
## 3. 打包步骤
### 3.1 一键打包命令
在项目根目录 `D:\Git\SikoraDaqReader` 下执行:
```powershell
# 1) 把 UPX 加入 PATH(供 PyInstaller 调用)
$env:Path = "D:\Git\SikoraDaqReader\PyApp\upx\upx-4.2.4-win64;$env:Path"
# 2) 把 PyInstaller 缓存重定向到项目内(见第 5.1 节说明)
$env:PYINSTALLER_CONFIG_DIR = "D:\Git\SikoraDaqReader\PyApp\pyicache"
# 3) (可选)清理上次产物
Remove-Item -Recurse -Force PyApp\build, PyApp\dist -ErrorAction SilentlyContinue
# 4) 执行打包
python -m PyInstaller PyApp\main.spec --noconfirm --distpath PyApp\dist --workpath PyApp\build
```
### 3.2 产物
- 输出文件:`PyApp/dist/SikoraDaqReader.exe`
- 体积:约 **27.6 MB**(单文件,无外部依赖)
- 直接双击即可运行
### 3.3 验证启动
```powershell
$p = Start-Process -FilePath "D:\Git\SikoraDaqReader\PyApp\dist\SikoraDaqReader.exe" -PassThru
Start-Sleep -Seconds 4
if ($p.HasExited) { Write-Output "FAILED code=$($p.ExitCode)" }
else { Write-Output "RUNNING_OK"; $p.Kill() }
```
---
## 4. 体积优化策略(main.spec 说明)
打包配置在 [main.spec](main.spec),采用以下手段将体积从默认 ~80 MB 压缩到 27.6 MB:
### 4.1 onefile 单文件
EXE 内嵌所有 binaries/datas,分发只需一个文件。
### 4.2 excludes 排除未使用的第三方库与 PyQt5 子模块
见 [main.spec 第 17-41 行](main.spec)。仅排除:
- **大型第三方库**:scipy / pandas / matplotlib / cv2 / h5py / lxml / sqlalchemy 等(环境中存在但本程序未使用)
- **PyQt5 子模块**:QtWebEngine / QtQml / QtQuick / QtMultimedia / QtNetwork / QtSvg 等 30+ 个(本程序仅用 QtCore/QtGui/QtWidgets)
- **第三方工具链**:setuptools / pip / ensurepip / wheel
> ⚠️ **绝对不能把 Python 标准库模块(urllib/http/xml/html/email 等)放入 excludes**,详见第 5.2 节。
### 4.3 过滤 a.binaries(仅保留必需 Qt5 DLL)
PyQt5 钩子会无条件收集整个 `Qt5\bin` 目录与全部插件,需在 [main.spec 的 _is_unneeded_binary](main.spec) 中手动过滤:
| 类别 | 处理 |
|------|------|
| Qt5*.dll | 仅保留 Qt5Core / Qt5Gui / Qt5Widgets,其余(Qt5Qml/Qt5Quick/Qt5Network/Qt5Svg/Qt5DBus...)全删 |
| OpenGL 相关 | 删除 opengl32sw.dll / d3dcompiler_47.dll / libEGL.dll / libGLESv2.dll(pyqtgraph 用 2D 绘图,不需要 OpenGL) |
| 平台插件 platforms | 仅保留 qwindows.dll,删除 qminimal/qoffscreen/qwebgl |
| QML 运行时 | 删除 /qml/ /qtqml/ 目录 |
| 其他插件 | 删除 mediaservice/audio/sqldrivers/sensors/printsupport/bearer/tls 等未用插件目录 |
| 图片格式 | 仅保留 gif/ico/jpeg/svg,删除 icns/tga/tiff/wbmp/webp |
### 4.4 UPX 压缩
`upx=True`,所有 DLL/PYD 经 UPX LZMA 压缩。
### 4.5 无控制台窗口
`console=False`(windowed 模式)。
### 4.6 优化效果
| 阶段 | 体积 | 手段 |
|------|------|------|
| 默认打包 | ~80 MB | — |
| + excludes 第三方库 | 40.4 MB | 排除 scipy/pandas/matplotlib/opencv 等 |
| + 排除 h5py | 35.3 MB | excludes 加 h5py(hdf5.dll 等) |
| + 过滤 Qt5 DLL/OpenGL/插件 | **27.6 MB** | _is_unneeded_binary 过滤 |
---
## 5. 常见问题与注意事项
### 5.1 `--clean` 报错 / bincache 损坏
**现象**:使用 `--clean` 时报 `OSError: [WinError 145] 目录不是空的` 或 `FileNotFoundError`,指向 `C:\Users\<user>\AppData\Local\pyinstaller\bincache01py31164bit\...`。
**原因**:`--clean` 会清理 AppData 下的 PyInstaller bincache,但该目录可能因权限/沙箱/旧缓存损坏而无法删除。
**解决**:**不要用 `--clean`**,改用环境变量 `PYINSTALLER_CONFIG_DIR` 把缓存重定向到项目内:
```powershell
$env:PYINSTALLER_CONFIG_DIR = "D:\Git\SikoraDaqReader\PyApp\pyicache"
```
这样 bincache 建在项目目录,可自由清理,且避开 AppData 的损坏缓存。修改 spec 的 excludes 后,配置哈希变化,旧缓存不会被复用,无需 `--clean`。
> 注意:环境变量名是 `PYINSTALLER_CONFIG_DIR`,不是 `PYINSTALLER_CACHE_DIR`。
### 5.2 `ModuleNotFoundError: No module named 'urllib'`
**现象**:exe 启动即崩溃,堆栈指向 `pyi_rth_inspect.py → pathlib.py → zipfile.py → ModuleNotFoundError: 'urllib'`。
**原因**:这是 PyInstaller **启动 runtime hook(rthook)阶段**的错误(应用代码尚未运行)。把标准库模块(urllib/http/xml/html/email 等)放入 `excludes` 会打断标准库内部的依赖链(pathlib/zipfile 间接依赖 urllib)。
**解决**:`excludes` **只能放第三方库和 PyQt5 子模块,绝不能放 Python 标准库模块**。若想缩减标准库,必须依赖 PyInstaller 自身的运行期分析,不要手动 exclude 顶层标准库名。
### 5.3 移除 OpenGL DLL 后能否正常运行
可以。pyqtgraph 的 PlotWidget 使用 QPainter(2D)绘图,不依赖 OpenGL。Qt5 在 Windows 上 2D 渲染走 GDI/CPU,无需 opengl32sw/libGLESv2/d3dcompiler。已通过启动验证。
### 5.4 杀毒软件误报
UPX 压缩的 exe 可能被部分杀毒软件误报。若介意,可在 [main.spec](main.spec) 中将 `upx=True` 改为 `upx=False`(体积会增大到约 45 MB)。
### 5.5 修改源码后重新打包
修改 `main.py` 后,重复执行第 3.1 节命令即可。PyInstaller 会增量打包,通常比首次快。若修改了 `main.spec` 的 excludes,建议先清理 `PyApp\build` 和 `PyApp\dist`。
---
## 6. 快速参考(复制即用)
```powershell
# 在项目根目录 D:\Git\SikoraDaqReader 下执行
$env:Path = "D:\Git\SikoraDaqReader\PyApp\upx\upx-4.2.4-win64;$env:Path"
$env:PYINSTALLER_CONFIG_DIR = "D:\Git\SikoraDaqReader\PyApp\pyicache"
Remove-Item -Recurse -Force PyApp\build, PyApp\dist -ErrorAction SilentlyContinue
python -m PyInstaller PyApp\main.spec --noconfirm --distpath PyApp\dist --workpath PyApp\build
```
产物:`PyApp\dist\SikoraDaqReader.exe`(约 27.6 MB)
+120
View File
@@ -0,0 +1,120 @@
# -*- mode: python ; coding: utf-8 -*-
"""PyInstaller spec: 将 main.py 打包为体积尽量小的单文件 exe。
体积优化手段:
1) onefile (EXE 内嵌 binaries/datas)
2) 排除未使用的大型第三方库与 PyQt5 子模块
(注意: 不排除任何标准库模块, 避免启动 rthook 阶段导入链断裂)
3) 过滤 a.binaries, 仅保留 Qt5Core/Qt5Gui/Qt5Widgets 三个必需 DLL
4) UPX 压缩 (运行打包时需把 upx 目录加入 PATH 或用 --upx-dir)
5) windowed (无控制台)
"""
import re
# 排除的模块: 仅排除本程序未用到的第三方库与 PyQt5 子模块
# 警告: 切勿把 Python 标准库模块(http/urllib/xml/html/email 等) 放入此列表,
# 否则 PyInstaller rthook 在启动阶段将因依赖链断裂而崩溃
# (如 ModuleNotFoundError: No module named 'urllib')
excluded_modules = [
# 大型第三方库 (环境中存在但本程序未使用)
'scipy', 'pandas', 'matplotlib', 'PIL', 'cv2', 'opencv', 'sklearn',
'sympy', 'tables', 'lxml', 'sqlalchemy', 'QCustomPlot_PyQt5',
'pyqt5_tools', 'pyqt5_plugins', 'h5py',
# PyQt5 中未使用的大模块 (这些是 PyQt5 的子模块, 非标准库)
'PyQt5.QtWebEngineCore', 'PyQt5.QtWebEngineWidgets',
'PyQt5.QtWebChannel', 'PyQt5.QtWebSockets',
'PyQt5.QtMultimedia', 'PyQt5.QtMultimediaWidgets',
'PyQt5.QtNetwork', 'PyQt5.QtSql', 'PyQt5.QtTest',
'PyQt5.QtSvg', 'PyQt5.QtSvgWidgets',
'PyQt5.QtOpenGL', 'PyQt5.QtBluetooth',
'PyQt5.QtSerialPort', 'PyQt5.QtSensors', 'PyQt5.QtPositioning',
'PyQt5.QtNfc', 'PyQt5.QtLocation', 'PyQt5.QtQuick', 'PyQt5.QtQml',
'PyQt5.QtQuickWidgets', 'PyQt5.QtDesigner', 'PyQt5.QtHelp',
'PyQt5.QtChart', 'PyQt5.QtDataVisualization',
'PyQt5.Qt3DCore', 'PyQt5.Qt3DRender', 'PyQt5.Qt3DInput',
'PyQt5.Qt3DLogic', 'PyQt5.Qt3DAnimation', 'PyQt5.Qt3DExtras',
'PyQt5.QtAxContainer', 'PyQt5.QtDBus', 'PyQt5.QtXml',
'PyQt5.QtPrintSupport', 'PyQt5.QtTextToSpeech',
'PyQt5.QtRemoteObjects', 'PyQt5.QtScript', 'PyQt5.QtScriptTools',
'PyQt5.QtUiTools',
# 同样是第三方工具链库, 本程序未使用
'setuptools', 'pip', 'ensurepip', 'wheel',
]
a = Analysis(
['main.py'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=excluded_modules,
noarchive=False,
)
def _is_unneeded_binary(name: str) -> bool:
"""过滤掉 PyQt5 钩子无条件收集、但本程序用不到的 Qt5 DLL / 插件 / qml 模块。
仅保留 Qt5Core/Qt5Gui/Qt5Widgets 以及 qwindows 平台插件等基础组件。
"""
n = name.replace('\\', '/').lower()
# Qt5*.dll 中除 Core/Gui/Widgets 外全部移除
m = re.search(r'qt5([a-z0-9]+)\.dll$', n)
if m and m.group(1) not in ('core', 'gui', 'widgets'):
return True
# QML / Quick 运行时目录(被 Qt5Quick 拖入, 本程序不用)
if '/qml/' in n or '/qtqml/' in n or '/qmltypes' in n or '/plugins/qml/' in n:
return True
# 不使用 OpenGL: 移除软件渲染器 / ANGLE / HLSL 编译器
if n.endswith(('opengl32sw.dll', 'd3dcompiler_47.dll', 'libegl.dll', 'libglesv2.dll')):
return True
# 平台插件只需 qwindows
if '/plugins/platforms/' in n and not n.endswith('qwindows.dll'):
return True
# Linux 桌面门户主题插件, Windows 不需要
if '/plugins/platformthemes/' in n:
return True
# 未使用的 Qt 插件子目录
for bad in ('/plugins/mediaservice/', '/plugins/audio/', '/plugins/sqldrivers/',
'/plugins/sensorgestures/', '/plugins/sensors/', '/plugins/position/',
'/plugins/geoservices/', '/plugins/printsupport/',
'/plugins/scenegraph/', '/plugins/sceneparsers/',
'/plugins/platforminputcontexts/', '/plugins/canbus/',
'/plugins/playlistformats/', '/plugins/bearer/',
'/plugins/gamepads/', '/plugins/tls/',
'/plugins/iconengines/', '/plugins/generic/'):
if bad in n:
return True
# 不常用的图片格式插件(保留 gif/ico/jpeg/svg)
if '/plugins/imageformats/' in n and n.endswith(
('qicns.dll', 'qtga.dll', 'qtiff.dll', 'qwbmp.dll', 'qwebp.dll')):
return True
return False
a.binaries = [b for b in a.binaries if not _is_unneeded_binary(b[0])]
a.datas = [d for d in a.datas if not _is_unneeded_binary(d[0])]
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='SikoraDaqReader',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=False,
disable_windowed_traceback=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon=None,
)