PyInstaller 是一个强大的 Python 打包工具,可将 Python 脚本转换为独立的可执行文件,在不同操作系统上运行,下面详细介绍其常用指令及使用方法。
基本使用
1. 安装 PyInstaller
在使用之前,你需要确保已经安装了 PyInstaller,若未安装,可以使用 pip
进行安装:
pip install pyinstaller
2. 基本打包命令
基本的打包命令格式为:
pyinstaller your_script.py
其中 your_script.py
是你要打包的 Python 脚本文件名。执行该命令后,PyInstaller 会分析脚本的依赖关系,将脚本和所需的依赖库打包成一个独立的可执行文件。打包完成后,会在项目目录下生成 build
和 dist
两个文件夹:
build
:包含打包过程中生成的临时文件。dist
:包含最终生成的可执行文件。
常用选项
1. 生成单个可执行文件
使用 --onefile
选项可以将所有依赖项打包到一个单独的可执行文件中,方便分发和使用。
pyinstaller --onefile your_script.py
2. 隐藏命令行窗口
如果你的 Python 脚本是一个 GUI 程序,使用 --windowed
(Windows)或 --noconsole
(macOS)选项可以在运行可执行文件时不显示命令行窗口。
# Windows 系统
pyinstaller --onefile --windowed your_script.py
# macOS 系统
pyinstaller --onefile --noconsole your_script.py
3. 指定图标
使用 --icon
选项可以为生成的可执行文件指定图标。图标文件必须是 .ico
格式(Windows)或 .icns
格式(macOS)。
# Windows 系统
pyinstaller --onefile --windowed --icon=your_icon.ico your_script.py
# macOS 系统
pyinstaller --onefile --noconsole --icon=your_icon.icns your_script.py
4. 添加额外的数据文件
如果你的项目依赖某些非 Python 库或外部文件,可能需要手动指定这些依赖项的路径。可以使用 --add-data
选项来添加额外的数据文件。
# Windows 系统
pyinstaller --onefile --add-data "config.ini;." your_script.py
# Linux 或 macOS 系统
pyinstaller --onefile --add-data "config.ini:." your_script.py
--add-data
选项的参数格式为 源文件路径;目标路径
(Windows 系统)或 源文件路径:目标路径
(Linux 或 macOS 系统),这里的 .
表示将文件添加到可执行文件所在的目录。
5. 指定工作目录
使用 --workpath
选项可以指定临时文件的生成目录。
pyinstaller --onefile --workpath=C:\temp your_script.py
6. 指定输出目录
使用 --distpath
选项可以指定最终可执行文件的输出目录。
pyinstaller --onefile --distpath=C:\output your_script.py
7. 清理临时文件
使用 --clean
选项可以在打包前清理之前生成的临时文件。
pyinstaller --onefile --clean your_script.py
8. 调试模式
使用 --debug
选项可以开启调试模式,查看详细的打包过程信息,帮助排查问题。
pyinstaller --onefile --debug your_script.py
示例
假设你有一个简单的 Python 脚本 main.py
,要将其打包成单个可执行文件,同时隐藏命令行窗口,并指定图标,可以使用以下命令:
# Windows 系统
pyinstaller --onefile --windowed --icon=app.ico main.py
# macOS 系统
pyinstaller --onefile --noconsole --icon=app.icns main.py
通过以上这些指令和选项,你可以根据项目的具体需求灵活地使用 PyInstaller 进行打包。
PS:
pyinstaller --windowed main.py