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

相关推荐
dialect_8 小时前
KMP算法
开发语言·c++·算法
总要学点什么9 小时前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
前端精髓9 小时前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣10 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
开开心心_Every10 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c10 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
Nuanyt10 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌10 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_9679873711 小时前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
超级架构师11 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core