python文件打包方式(使用pyinstaller)
作者:安生生申
这段描述主要介绍了PyInstaller的使用方法,包括如何通过pip安装PyInstaller,如何使用简单命令和复杂命令进行打包,以及如何通过编写打包脚本进行操作,同时提到了在打包过程中可能出现的PIL模块错误,并提供了相应的解决方法
PyInstaller是一个流行的Python打包工具,它可以将Python代码打包成可执行文件,使得你可以在没有安装Python解释器的环境中运行你的应用程序。
安装
使用pip命令来安装PyInstaller。在终端或命令提示符中运行以下命令:
打包
先安装所有需要的依赖
pip install -r .\requirements.txt
方式一:使用打包命令
简单命令:
pyinstaller main.py
复杂命令:
Window - Powershell:
pyinstaller -n SnakeGame `
-i img/icon.png `
--clean --onedir `
--windowed `
--add-data="img;img" `
--exclude-module="numpy" `
main.pyWindow - cmd:
# 打包到一个目录 pyinstaller -n PID_Tool -i img/logo.ico ^ --clean --onedir ^ --add-data="res;res" ^ --add-data="img;img" ^ --exclude-module="matplotlib" ^ app.py
Linux/Mac:
# 打包成单文件 pyinstaller -n PID_Tool -i img/logo.ico \ --clean --onefile \ --add-data="res:res" \ --add-data="img:img" \ --exclude-module="matplotlib" \ main.py
方式二:编写打包脚本
假如你的程序名称为PID_GUI_Tool,程序入口文件为main.py,则在入口文件同级目录创建一个package.py,写入如下内容
import PyInstaller.__main__
# 这里的是不需要打包进去的三方模块,可以减少软件包的体积
excluded_modules = [
"scipy",
"matplotlib",
]
append_string = []
for mod in excluded_modules:
append_string += [f'--exclude-module={mod}']
PyInstaller.__main__.run([
'-y', # 如果dist文件夹内已经存在生成文件,则不询问用户,直接覆盖
# '-p', 'src', # 设置 Python 导入模块的路径(和设置 PYTHONPATH 环境变量的作用相似)。也可使用路径分隔符(Windows 使用分号;,Linux 使用冒号:)来分隔多个路径
'main.py', # 主程序入口
'--onedir', # -D 文件夹
# '--onefile', # -F 单文件
# '--nowindowed', # -c 无窗口
'--windowed', # -w 有窗口
'-n', 'PID_GUI_Tool',
'-i', 'img/logo.ico',
'--add-data=res;res', # 用法:pyinstaller main.py –add-data=src;dest。windows以;分割,mac,linux以:分割
'--add-data=img;img', # 用法:pyinstaller main.py –add-data=src;dest。windows以;分割,mac,linux以:分割
*append_string
])
执行python package.py或直接在编辑器中运行即可。
打好包,可执行程序在同级目录的dist子目录即可找到
问题及解决
如果打包时,出现如下报错:
from PIL import Image
ModuleNotFoundError: No module named 'PIL'
可通过安装如下依赖解决:
pip install pillow
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
