PyInstaller打包Astropy程序报错:未找到PIL包元数据
PyInstaller打包Astropy可视化程序时出现PIL元数据缺失错误
我从Astropy官网复制的示例小程序在PyCharm中运行完全正常,但用PyInstaller打包成可执行文件后,启动时抛出如下错误:
Importlib.metadata.PackageNotFoundError: No package metadata was found for PIL
原程序代码
import matplotlib.pyplot as plt from astropy.visualization import ImageNormalize, ZScaleInterval, LinearStretch from importlib_metadata import metadata from astropy.wcs import WCS from astropy.io import fits reference_image = "C:/Users/Michel/Documents/Astrophotography/MCD Images/SN_Pipeline_Reference/A8 Reference.fits" science_image = "C:/Users/Michel/Documents/Astrophotography/MCD Images/SN_Pipeline_Science/A8/A8_Registered1.fit" plots_path = "C:/Users/Michel/Documents/Astrophotography/MCD Images/SN_Pipeline_Science/A8/" hdu = fits.open(reference_image)[0] hdu1 = fits.open(science_image)[0] wcs = WCS(hdu.header) norm = ImageNormalize(hdu.data, interval=ZScaleInterval(), stretch=LinearStretch()) plt.subplot(projection=wcs) plt.imshow(hdu1.data, cmap='gray', norm=norm, interpolation='none') plt.grid(color='white', ls='solid') plt.xlabel('Galactic Longitude') plt.ylabel('Galactic Latitude') plt.show()
已尝试的操作
- 升级astropy至5.3.4版本
- 升级matplotlib至3.8.1版本
- 升级Pillow至10.1.0版本
- 升级importlib-metadata至6.8.0版本
解决方案
这个问题是因为PyInstaller自动依赖检测机制遗漏了PIL(Pillow)的元数据文件导致的,可通过以下方式解决:
- 显式导入PIL
在代码开头添加一行导入语句,让PyInstaller强制捕获这个依赖:
import PIL # 显式导入以帮助PyInstaller识别依赖
- 打包时指定隐藏导入
执行PyInstaller打包命令时,通过--hidden-import参数明确指定PIL:
pyinstaller --hidden-import=PIL your_script_name.py
- 修改spec文件(若使用spec打包)
如果通过spec文件进行打包,打开对应的.spec文件,在hiddenimports列表中添加'PIL':
hiddenimports=['PIL'],
保存后重新执行打包:
pyinstaller your_script_name.spec
- 验证Pillow安装有效性
确认Pillow是通过pip正常安装在标准site-packages目录下,执行以下命令查看安装路径:
pip show Pillow
若安装路径异常,建议重新安装Pillow:
pip uninstall Pillow pip install Pillow
内容的提问来源于stack exchange,提问作者Michel Michaud
相关产品推荐
相关产品推荐

