python打包工具PyInstaller
PyInstaller 是一个用于将 Python 程序打包成独立可执行文件的工具,支持 Windows、Linux 和 macOS。
1、安装PyInstaller
pip install pyinstaller
2、使用方法
2.1 简单应用
# 基本打包命令
pyinstaller your_script.py
# 打包成单个文件
pyinstaller -F your_script.py
# 打包成单个文件(不显示控制台窗口,适合GUI程序)
pyinstaller -F -w your_script.py
2.2常用参数说明
|
参数 |
说明 |
示例 |
|
-F, --onefile |
打包成单个可执行文件 |
pyinstaller -F app.py |
|
-D, --onedir |
打包成一个文件夹(默认) |
pyinstaller -D app.py |
|
-w, --windowed |
不显示控制台窗口 |
pyinstaller -w app.py |
|
-c, --console |
显示控制台窗口(默认) |
pyinstaller -c app.py |
|
-n NAME, --name NAME |
指定生成文件名 |
pyinstaller -n MyApp app.py |
|
-i ICON, --icon ICON |
设置程序图标 |
pyinstaller -i icon.ico app.py |
|
--add-data SRC:DST |
添加额外文件 |
--add-data "data/*:data" |
|
--add-binary SRC:DST |
添加二进制文件 |
--add-binary "lib/*:lib" |
|
--hidden-import MODULE |
添加隐藏导入的模块 |
--hidden-import pandas |
|
--exclude-module MODULE |
排除不需要的模块 |
--exclude-module matplotlib |
|
--clean |
清理临时文件 |
pyinstaller --clean app.py |
|
--upx-dir DIR |
指定 UPX 压缩工具目录 |
--upx-dir C:\upx |
|
-y, --noconfirm |
覆盖输出目录不确认 |
pyinstaller -y app.py |
2.3简单示例
示例一:基本打包
demo.py文件内容为“print('你好')”

使用命令“pyinstaller demo.py”进行打包,打包成功会显示“successfully”。


打包后会生成build、dist文件夹,spec文件。

spec文件为配置文件,配置文件可以修改,修改会影响后续打包。
build为打包时的临时构建文件,打包后可以删除,没有影响。
dist为可执行文件所在目录,存放exe可执行文件及各种依赖文件。

将dist下整个demo文件夹复制到没有python环境的设备上也可以运行。
点击shift+鼠标右键,打开powershell窗口,运行demo.exe,结果如下:

示例二:带图标的单个可执行文件
demo.py文件同路径下放ico图片,使用命令“pyinstaller -F -i icon.ico demo.py”进行打包

打包后如下图,只有一个可执行文件。

2.4 常见问题
2.4.1添加隐藏导入
pyinstaller --hidden-import=pandas --hidden-import=numpy app.py
2.4.2排除不需要的模块
pyinstaller --exclude-module=matplotlib --exclude-module=scipy app.py
2.4.3路径处理
程序打包后,在运行时会解压到系统临时目录(如 sys._MEIPASS)。如果直接用相对路径找资源,打包后会失效打,所以需要对路径进行处理。
import sys
import os
def resource_path(relative_path):
"""获取资源文件的绝对路径"""
try:
# PyInstaller 打包后的程序运行时,会自动创建一个临时目录存放解压后的资源,该目录的路径会被赋值给 sys._MEIPASS
# 如果能够获取到sys._MEIPASS,说明程序是打包后的可执行文件
base_path = sys._MEIPASS
except AttributeError:
# 若获取不到sys._MEIPASS,会触发异常,然后获取源码所在的绝对目录
base_path = os.path.abspath(".")
# 拼接接待路径并返回
return os.path.join(base_path, relative_path)
3、selenium+python程序打包
selenium程序打包时需要注意driver文件。有三种方案:
|
方案 |
核心特点 |
适用场景 |
|
驱动打进exe内 |
单文件分发,无需额外文件,便携性最高 驱动版本不同需要重新打包 |
需离线运行、分发简单的场景 |
|
驱动放在exe外部 |
可灵活更换驱动版本,无需重新打包 |
需频繁调整驱动版本的测试场景 |
|
Selenium自动下载 |
无需手动管理驱动,代码最简洁 联网下载有时候不成功(目前还未解决该问题) |
联网环境、Selenium ≥4.6.0 的场景 |
3.1将driver文件打包到程序包中
举例:打开百度网页。
baidu.py文件中的代码为:
import os
import sys
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
def get_chromedriver_path():
# 判断是否是打包后的exe运行环境
if getattr(sys, 'frozen', False):
# 打包后:exe解压的临时目录(_MEIxxxxxx)
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
else:
# 开发环境:当前文件所在目录,将chromedriver.exe和baidu.py放同一个目录下了
base_path = os.path.dirname(os.path.abspath(__file__))
# 拼接驱动路径(无论哪种环境,都找 base_path 下的 chromedriver.exe)
driver_path = os.path.join(base_path, "chromedriver.exe")
return driver_path
driver_path = get_chromedriver_path()
# 初始化 driver
service = Service(executable_path=driver_path)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# 打开一个网站,这里以百度为例
driver.get('https://www.baidu.com')
driver.maximize_window()
time.sleep(5)
# 最后关闭驱动
driver.quit()
在baidu.py所在目录使用命令 pyinstaller -F --add-binary "chromedriver.exe;." baidu.py 进行打包。(也可以用全路径打包pyinstaller -F --add-binary "G:\test\chromedriver.exe;." G:\test\baidu.py)

直接运行打包生成的exe文件即可。

3.2将driver文件放在打包软件的文件夹下
举例:打开百度网页。
baidu.py文件中的代码为:
def get_chromedriver_path():
if getattr(sys, 'frozen', False):
# 打包后:读取 exe 所在目录的 chromedriver.exe(而非临时目录)
exe_dir = os.path.dirname(sys.executable) # exe 所在文件夹路径
driver_path = os.path.join(exe_dir, "chromedriver.exe")
else:
# 开发环境:读取当前文件目录的驱动
driver_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chromedriver.exe")
return driver_path
driver_path = get_chromedriver_path()
# 初始化 driver
service = Service(executable_path=driver_path)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)
# 打开一个网站,这里以百度为例
driver.get('https://www.baidu.com')
driver.maximize_window()
time.sleep(5)
# 最后关闭驱动
driver.quit()
在baidu.py所在目录使用命令 pyinstaller -F -w baidu.py 进行打包。(也可以用全路径打包pyinstaller -F -w G:\test\testcase\baidu.py)

将chromedriver.exe放在打包生成的exe文件同一目录下,在运行exe文件即可。

3.3自动下载驱动
当Selenium 版本 ≥4.6.0,可放弃手动管理驱动,让Selenium自动下载匹配版本的驱动。例:
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# 配置 Chrome 选项
options = Options()
# 屏蔽无关日志(可选)
options.add_experimental_option('excludeSwitches', ['enable-logging'])
# 核心:Selenium 4.6+ 自动管理驱动,无需传 Service 和驱动路径
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get('https://www.baidu.com')
time.sleep(10)
driver.quit()
可使用命令 pyinstaller -F -w G:\test\testcase\baidu.py 打包。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)