Ubuntu24.04 Python3.12.4虚拟环境中Pillow导入失败的解决办法
解决Pillow导入_imaging失败的问题
你遇到的ImportError: cannot import name '_imaging'是因为Pillow的核心C扩展模块未正确编译生成,以下是具体解决步骤:
卸载现有Pillow并清理残留
先彻底移除当前安装的Pillow及残留文件,避免干扰重新安装:pip uninstall -y pillow rm -rf /mnt/SystemData/venvs/PRD/lib/python3.12/site-packages/PIL/安装Pillow编译依赖
Ubuntu系统下编译Pillow需要基础编译工具和图像格式依赖包,执行以下命令安装:sudo apt update sudo apt install build-essential python3.12-dev libjpeg-dev libpng-dev libtiff-dev libwebp-dev这些依赖是生成
_imaging.so模块的必要条件,缺失会导致编译跳过该模块。重新编译安装Pillow
激活虚拟环境后,强制从源码编译安装Pillow,确保系统依赖被正确调用:source /mnt/SystemData/venvs/PRD/bin/activate pip install --no-binary :all: pillow==10.4.0--no-binary :all:参数会让pip放弃预编译包,从源码编译生成适配当前环境的C扩展模块。验证安装结果
安装完成后,进入Python交互环境验证:from PIL import Image # 检查核心模块是否存在 import PIL._imaging print(PIL._imaging.__file__)若能正常导入并打印出
_imaging.so的路径,说明问题已解决。额外排查方向
- 确认虚拟环境激活状态:执行
which python,输出应为/mnt/SystemData/venvs/PRD/bin/python,避免误操作到系统Python。 - 查看编译日志:若仍失败,重新安装时添加
-v参数查看编译错误细节:pip install -v --no-binary :all: pillow==10.4.0
- 确认虚拟环境激活状态:执行
内容的提问来源于stack exchange,提问作者Jonathan
相关产品推荐
相关产品推荐

