python 文件打包(使用pyinstaller)

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.py

Window - 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

  • 20
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值