打包出现的问题
FileNotFoundError: [Errno 2] No such file or directory: ‘C:\gradio_client\types.json’
[11896] Failed to execute script ‘Photo_ID’ due to unhandled exception!
解决方案
采用PyInstaller进行打包
PyInstaller 是一个强大的工具,用于将 Python 程序打包成独立的可执行文件,使其能够在没有 Python 解释器的环境中运行。
依赖库
pip install pyinstaller
进行打包
pyinstaller -F Photo_ID.py
Photo_ID.py:为需要打包的.py文件
程序出现闪退,在cmd中进行执行exe文件,可查看具体报错原因
PyInstaller 有时不能准确识别某些库的依赖项,特别是像 gradio_client 和 gradio 这样的库。在这种情况下,可以通过在打包命令中显式添加这些依赖项来解决问题。
pyinstaller -F Photo_ID.py --collect-data=gradio_client --collect-data=gradio
出现以下报错:
FileNotFoundError: [Errno 2] No such file or directory: ‘C:\gradio\blocks_events.pyc’
[43252] Failed to execute script ‘Photo_ID’ due to unhandled exception!
解决方案:
打开与要打包py代码同名的spec文件,添加对gradio的编译
module_collection_mode={ 'gradio': 'py',}
# -*- mode: python ; coding: utf-8 -*-
from PyInstaller.utils.hooks import collect_data_files
datas = []
datas += collect_data_files('gradio_client')
datas += collect_data_files('gradio')
a = Analysis(
['Photo_ID.py'],
pathex=[],
binaries=[],
datas=datas,
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
noarchive=False,
optimize=0,
module_collection_mode={'gradio':'py',}, #添加
)
pyz = PYZ(a.pure)
exe = EXE(
pyz,
a.scripts,
[],
exclude_binaries=True,
name='证件照背景一键转换', #命名
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
icon='./myicon.ico' #图标
)
coll = COLLECT(
exe,
a.binaries,
a.datas,
strip=False,
upx=True,
upx_exclude=[],
name='Photo_ID',
)
修改后,删除build文件夹,执行 pyinstaller Photo_ID.spec
运行exe文件