PyInstaller 是一个跨平台的工具,它的主要功能包括
使用 pip 安装 PyInstaller:
1 |
pip install pyinstaller |
检查安装是否成功:
1 |
pyinstaller --version |
假设你的脚本名为 app.py,可以运行以下命令:
1 |
pyinstaller app.py |
完成后,PyInstaller 会生成以下内容:
生成的可执行文件位于 dist/app 目录下。
默认情况下,PyInstaller 会生成一个包含多个文件的目录。如果希望生成一个独立的单文件可执行文件,可以加上 --onefile 参数:
1 |
pyinstaller --onefile app.py |
可以通过 --icon 参数为程序添加自定义图标(支持 .ico 格式):
1 |
pyinstaller --onefile --icon=myicon.ico app.py |
对于图形化应用程序,可以隐藏运行时弹出的控制台窗口,使用 --noconsole 参数:
1 |
pyinstaller --onefile --noconsole app.py |
可以通过 --distpath 和 --workpath 参数指定输出目录和临时文件目录:
1 |
pyinstaller --onefile --distpath ./output --workpath ./temp app.py |
PyInstaller 生成的 .spec 文件是一个配置脚本,包含了打包过程中的所有参数。你可以编辑这个文件,然后使用以下命令重新打包:
1 |
pyinstaller app.spec |
PyInstaller 会打包所有依赖项,导致生成的可执行文件体积较大。可以尝试以下方法优化:
1 |
pyinstaller --onefile --upx-dir=/path/to/upx app.py |
可能原因:
1 |
pyinstaller --onefile --hidden-import=<module_name> app.py |
对于复杂的项目,打包可能耗时较长。可以使用 --clean 参数清理临时文件,加快后续的打包速度。
工具 | 优点 | 缺点 |
---|---|---|
PyInstaller | 跨平台,支持多种模式 | 打包文件较大,依赖 Python 环境 |
cx_Freeze | 支持更多细粒度的打包控制 | 配置复杂 |
py2exe | 专注于 Windows 平台 | 仅支持 Windows |
py2app | 专注于 macOS 平台 | 仅支持 macOS |
以下命令将脚本 app.py 打包为单文件可执行程序,附带图标,并隐藏控制台窗口:
1 |
pyinstaller --onefile --icon=myicon.ico --noconsole app.py |
PyInstaller 是一个非常实用的工具,适合需要分发 Python 应用程序的开发者。通过 PyInstaller,可以将 Python 程序变成独立的可执行文件,免去用户配置环境的烦恼。