之前的博客提到过如果 python 安装的第三方包太多的话(且没有为每个项目单独安装虚拟 python 环境),会导致打包后的 exe 文件比较臃肿,而且很可能这些包在我们打包的程序里其实根本用不着,这时候我们可以再在 spec 文件添加 excludes 参数排除部分比较重且用不到的模块。
但是,我们要怎么能快速获取到哪些包比较重且我们打包程序是不需要的呢?
我们可以利用 pkg_resources 获取安装包目录列表,然后计算对应的包所占磁盘的空间。比如我们筛选出空间占用大于 10M 的安装包。
python
import os
import pkg_resources
def get_size(path):
total = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
total += os.path.getsize(fp)
return total
for dist in pkg_resources.working_set:
try:
# 包的实际路径通常是 location/package_name
path = os.path.join(dist.location, dist.project_name)
size_mb = get_size(path) / 1024.0 / 1024.0
if size_mb > 10: # 只显示大于10M的包
print(f"{dist.key}: {size_mb:.2f} MB")
except OSError:
# 处理包路径不存在的情况
pass
python
faker: 15.05 MB
pip: 13.70 MB
plotly: 88.53 MB
chardet: 20.76 MB
pyqt5: 142.24 MB
fonttools: 15.15 MB
matplotlib: 27.75 MB
pandas: 62.98 MB
playwright: 102.04 MB
numpy: 64.67 MB
onnxruntime: 35.32 MB
scipy: 120.88 MB
sympy: 70.25 MB
debugpy: 31.14 MB
ddddocr: 84.08 MB
jieba: 41.08 MB
statsmodels: 47.52 MB
sqlalchemy: 17.08 MB
在使用 pyinstaller 打包的时候,使用 excludes 参数排除掉空间占用高且用不到的模块。
python
a = Analysis(
# ...
excludes=['ddddocr', 'pandas', 'numpy', 'pyqt5', 'playwright'], # 在这里添加
# ...
)
python
pyinstaller ./test.spec
当然,如果你已经使用了虚拟环境,且只安装了项目需要的必要依赖,那就没有此烦恼了。