python 文件打包(使用pyinstaller)

发布于:2024-04-23 ⋅ 阅读:(158) ⋅ 点赞:(0)

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


网站公告

今日签到

点亮在社区的每一天
去签到