PyInstaller¶
263238¶
282c34¶
242835¶
1. 安装¶
pip install PyInstaller
2. 带参数打包¶
-
-F:打包为单文件-
-w:隐藏控制台(适合GUI程序)-
-i:指定exe图标(需.ico格式)
3. 输出结构¶
- 生成
dist文件夹包含exe文件 build文件夹为临时文件可删除
4. 使用UPX压缩¶
upx: UPX - the Ultimate Packer for eXecutables
解压后,将UPX所在目录加入系统PATH
添加系统变量后,PyInstaller 打包时会自动检测并使用 UPX 压缩:
pyinstaller -F -w your_script.py
一、动态导入模块未被识别的解决方法¶
-
显式指定隐藏模块
PyInstaller无法自动检测动态导入的模块(如importlib.import_module()或条件导入),需通过--hidden-import手动添加:示例:若动态导入
comtypes.stream,则添加--hidden-import=comtypes.stream3 4 5。 -
修改
.spec文件
在生成的.spec文件中,找到Analysis段,添加hiddenimports列表:例如,添加
hiddenimports=['sklearn.utils._cython_blas']解决缺失的隐式依赖2 8 9。
二、静态文件(非代码资源)未打包的解决方法¶
-
通过命令行添加资源
使用--add-data参数指定资源路径,格式为源路径;目标路径:bash
此命令会将本地
config.json和templates/目录下的文件打包到生成的临时目录中5 6 10。 -
在
.spec文件中配置datas
编辑.spec文件的Analysis段,添加datas元组列表:python
例如,
datas=[('static/images', 'images')]会将本地static/images目录打包到临时目录的images下
打包命令优化:¶
启用多核编译
```python
python -m PyInstaller --noconfirm --clean --log-level WARN auto_generated.spec
强制清理缓存
python
python -m PyInstaller --clean --noconfirm auto_generated.spec