安装PyInstaller
确保Python环境已配置,通过pip命令安装PyInstaller:
pip install pyinstaller
验证安装是否成功:
pyinstaller --version
基本打包命令
使用单文件模式打包Python脚本:
pyinstaller --onefile your_script.py
生成的可执行文件位于dist
目录下。
添加依赖文件
若脚本依赖外部资源(如图片、数据文件),通过--add-data
参数指定:
pyinstaller --onefile --add-data "source_path;dest_path" your_script.py
路径分隔符在Windows中使用;
,在Linux/macOS中使用:
。
自定义图标和元数据
为可执行文件添加图标(需.ico
格式):
pyinstaller --onefile --icon=your_icon.ico your_script.py
通过--version-file
指定版本信息文件(仅Windows支持)。
排除不必要的模块
减少打包体积,使用--exclude-module
排除未使用的库:
pyinstaller --onefile --exclude-module unused_module your_script.py
处理打包后的路径问题
在脚本中使用sys._MEIPASS
访问临时资源路径:
import sys
import os
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
调试打包错误
查看详细日志定位问题:
pyinstaller --debug all your_script.py
检查生成的.spec
文件,手动调整配置后重新打包:
pyinstaller your_script.spec
高级选项
- 加密字节码:使用
--key
参数(需安装tinyaes
)。 - 多平台交叉打包:通过虚拟机或Docker容器生成目标平台的可执行文件。
- 减小体积:结合UPX压缩工具(通过
--upx-dir
指定路径)。