跳转至

PyInstaller

263238

282c34

242835

1. 安装

pip install PyInstaller

2. 带参数打包

pyinstaller -F -w -i icon.ico your_script.py

- -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

一、动态导入模块未被识别的解决方法

  1. 显式指定隐藏模块
    PyInstaller无法自动检测动态导入的模块(如importlib.import_module()或条件导入),需通过--hidden-import手动添加:

    pyinstaller --hidden-import=模块名 --hidden-import=子模块名 your_script.py
    

    示例:若动态导入comtypes.stream,则添加--hidden-import=comtypes.stream3 4 5

  2. 修改.spec文件
    在生成的.spec文件中,找到Analysis段,添加hiddenimports列表:

    a = Analysis(    ...,    hiddenimports=['模块名', '子模块名'],)
    

    例如,添加hiddenimports=['sklearn.utils._cython_blas']解决缺失的隐式依赖2 8 9


二、静态文件(非代码资源)未打包的解决方法

  1. 通过命令行添加资源
    使用--add-data参数指定资源路径,格式为源路径;目标路径

    bash

    pyinstaller --add-data="config.json;." --add-data="templates/*;templates/" your_script.py
    

    此命令会将本地config.jsontemplates/目录下的文件打包到生成的临时目录中5 6 10

  2. .spec文件中配置datas
    编辑.spec文件的Analysis段,添加datas元组列表:

    python

    a = Analysis(    ...,    datas=[('本地资源路径', '目标目录名'), ('config.json', '.')],)
    

    例如,datas=[('static/images', 'images')]会将本地static/images目录打包到临时目录的images

打包命令优化:

启用多核编译
```python
python -m PyInstaller --noconfirm --clean --log-level WARN auto_generated.spec

 显示详细打包过程
  ```python
python -m PyInstaller --log-level DEBUG auto_generated.spec

强制清理缓存
python python -m PyInstaller --clean --noconfirm auto_generated.spec