python 文件打包(使用pyinstaller)

PyInstaller是一个流行的Python打包工具,它可以将Python代码打包成可执行文件,使得你可以在没有安装Python解释器的环境中运行你的应用程序。:

安装

使用pip命令来安装PyInstaller。在终端或命令提示符中运行以下命令:

打包

先安装所有需要的依赖

pip install -r .\requirements.txt

方式一:使用打包命令

简单命令:

pyinstaller main.py

复杂命令:

Window - Powershell:

python 复制代码
pyinstaller -n SnakeGame `
        -i img/icon.png `
		--clean --onedir `
    	--windowed `
		--add-data="img;img" `
		--exclude-module="numpy" `
		main.py

Window - cmd:

python 复制代码
# 打包到一个目录
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:

python 复制代码
# 打包成单文件
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,写入如下内容

python 复制代码
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

相关推荐
hqxstudying几秒前
Java创建型模式---原型模式
java·开发语言·设计模式·代码规范
charlie11451419116 分钟前
如何使用Qt创建一个浮在MainWindow上的滑动小Panel
开发语言·c++·qt·界面设计
孤狼warrior19 分钟前
灰色预测模型
人工智能·python·算法·数学建模
神仙别闹24 分钟前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
机器学习之心1 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
JavaEdge在掘金1 小时前
MySQL 8.0 的隐藏索引:索引管理的利器,还是性能陷阱?
python
站大爷IP1 小时前
Python办公自动化实战:手把手教你打造智能邮件发送工具
python
chao_7891 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
zdw2 小时前
fit parse解析佳明.fit 运动数据,模仿zwift数据展示
python
剑桥折刀s2 小时前
Python打卡:Day46
python