PyInstaller 是一个将 Python 脚本打包成独立可执行文件(例如 Windows 系统的.exe)的工具,方便在没有 Python 环境的机器上运行程序

安装 pyinstaller

在项目 python 环境的终端执行:

1
$ pip install pyinstaller

使用 pyinstaller 命令打包 python 脚本

  • 在脚本所在目录终端中执行:
1
2
3
4
# 创建带有控制台窗口的可执行文件及运行库文件(文件夹)
$ pyinstaller your_script.py
# 创建去除控制台窗口,自定义图标的单个可执行程序(文件)
$ pyinstaller -F -w -i your_icon.ico your_script.py

执行后会生成 build、dist 文件夹和 .spec 配置文件,dist 中的文件即为打包完成的可执行文件

常用参数:

1
2
3
4
5
6
-F , --onefile:打包成单个可执行文件
-D , --onedir:打包成文件夹(默认)
-w , --windowed:去除控制台窗口(适合 GUI 程序)
-c , --console:保留控制台窗口(默认)
-i , --icon:指定图标文件
--add-data:添加资源文件(格式:源路径:目标路径)

注意:如果 python 脚本中使用了图片等相关资源,如果直接进行打包可能导致生成的可执行文件运行时找不到该图片而报错,需要使用--add-data参数或者对 python 脚本中的图片等资源路径进行处理

参考:
Using PyInstaller — PyInstaller 6.17.0 documentation
使用 PyInstaller 打包 Python 项目(多文件、图标、附件支持)——详尽指南
【Python 教程】保姆版教使用 Pyinstaller 打包 python 成 exe 文件_pytinstaller-CSDN 博客