使用Pyarmor打包Python项目为EXE时遇PIL依赖及matplotlib路径错误
解决Pyarmor打包时PyInstaller的两类报错
一、ModuleNotFoundError: 找不到PIL模块
- 先确认当前环境已正确安装Pillow(PIL的替代库),执行
pip install pillow;如果已安装,重新安装确保无损坏:pip install --force-reinstall pillow - 在打包命令的
-e参数里添加--hidden-import PIL(若代码用到PIL子模块如Image,就加--hidden-import PIL.Image),强制PyInstaller识别该依赖 - 确保打包时激活了正确的虚拟环境,避免用全局Python环境的包,防止依赖路径混乱
二、matplotlib钩子触发AssertionError:无法确定数据目录
- 在打包命令里添加
--collect-data matplotlib,让PyInstaller自动收集matplotlib的所有数据文件,解决目录识别问题 - 升级PyInstaller到最新版本,旧版本的matplotlib钩子存在bug:
pip install --upgrade pyinstaller - 也可以在代码开头临时指定matplotlib的配置目录,避免读取系统路径出错:
import os import tempfile os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
修改后的打包命令示例
pyarmor pack -e " --icon chainsaw.ico --onefile --add-binary 'C:/Python310/Lib/site-packages/tls_client/dependencies/tls-client-64.dll;tls_client/dependencies' --hidden-import PIL --collect-data matplotlib" main.py
额外排查步骤
- 先尝试用纯PyInstaller打包(去掉
pyarmor pack,直接用pyinstaller命令),如果能成功,说明问题出在Pyarmor和PyInstaller的配合上,可先打包成未加密的EXE再用Pyarmor加密;如果纯PyInstaller也报错,就专注解决PyInstaller本身的依赖问题 - 检查项目的requirements.txt,确保Pillow和matplotlib都在列表里,且版本与当前环境一致
内容的提问来源于stack exchange,提问作者drag
相关产品推荐
相关产品推荐

