前言:
Python有很多优秀的第三方库,相当方便扩充各种能力,提高编程效率。但当我们安装了很多第三方库,在用Pyinstaller进行打包为exe文件,尤其是为了分发方便,将代码打包为一个exe文件的时候,有时会莫名的将许多代码中没有使用到的DLL文件也加进去,导致exe文件非常臃肿庞大。
优化:
1、使用干净的虚拟环境,只安装项目中真正需要的库,避免全局安装的库被误打包。
# 创建虚拟环境
python -m venv myenv
# 激活虚拟环境(Windows)
myenv\Scripts\activate
# 安装必要的库
pip install pyinstaller
pip install -r requirements.txt # 只包含项目实际需要的包
2、使用 UPX 压缩可执行文件
# 下载 UPX: https://upx.github.io
# 解压后指定 UPX 目录
pyinstaller --onefile --upx-dir=C:\path\to\upx your_app.py
3、编辑 .spec
文件,修改 Analysis
部分中的excludes字段:
可以在命令行下,先用如:pyi-archive_viewer E:\edge_auto\dist\Automation.exe分析打包好的exe文件,可以看到类似的信息:
C:\Users\Administrator>pyi-archive_viewer E:\edge_auto\dist\Automation.exe
Options in 'Automation.exe' (PKG/CArchive):
pyi-contents-directory _internal
Contents of 'Automation.exe' (PKG/CArchive):
position, length, uncompressed_length, is_compressed, typecode, name
...
19885935, 2397724, 5422816, 1, 'b', 'selenium\\webdriver\\common\\linux\\selenium-manager'
22283659, 4074912, 8076960, 1, 'b', 'selenium\\webdriver\\common\\macos\\selenium-manager'
26358571, 860, 1944, 1, 'b', 'selenium\\webdriver\\common\\mutation-listener.js'
26359431, 1887296, 3686912, 1, 'b', 'selenium\\webdriver\\common\\windows\\selenium-manager.exe'
29242131, 1723364, 2469156, 1, 'b', 'tessdata\\chi_sim.traineddata'
30965495, 1967587, 4113088, 1, 'b', 'tessdata\\eng.traineddata'
32933082, 4274621, 10562727, 1, 'b', 'tessdata\\osd.traineddata'
37207703, 44056, 86152, 1, 'b', 'tesseract.exe'
37251759, 727380, 1591656, 1, 'b', 'tk86t.dll'
...
比如上面的分析中,如你的exe文件不需要在linux和macos系统中使用,可以在对应的spec文件中这样修改排除打包:
a = Analysis(
...
excludes=[
'selenium.webdriver.common.linux',
'selenium.webdriver.common.macos',
# 其他冗余模块
],
如果OCR不用处理中文字符,可以将:essdata目录下的chi_sim.traineddata和osd.traineddata文件删除,可能显著减少文件体积。