首页 > 解决方案 > Python层图像失败:“无法导入模块'lambda_function':无法从'PIL'导入名称'_imaging'”

问题描述

我只是想在我的 Python 3.8 Lambda 中使用 PIL。

我正在尝试以下步骤:

  1. 基于此回购:https ://github.com/hidekuma/lambda-layers-for-python-runtime
cd /mydir 
git clone https://github.com/hidekuma/lambda-layers-for-python-runtime.git 
cd lambda-layers-for-python-runtime 
mkdir dist 
docker-compose up --build
  1. 基于此指南:https ://www.splunk.com/en_us/blog/cloud/sharing-code-dependencies-with-aws-lambda-layers.html
aws lambda publish-layer-version --layer-name ImageStorageDependencies
    --description "A Python 3.8 runtime with PIL and boto3 installed." --license-info "MIT" --zip-file fileb://output.zip --compatible-runtimes python3.7 python3.8 --region us-east-2

然后我在 Lamda 配置中选择我的层,但是当我运行此代码时:

import json
import boto3
import io
from PIL import Image


def lambda_handler(event, context): 
    #etc

...我得到错误:

[ERROR] Runtime.ImportModuleError: Unable to import module 'lambda_function': cannot import name '_imaging' from 'PIL' 

我到底哪里错了?!?

标签: pythonaws-lambdaaws-lambda-layers

解决方案


澄清一下,关于您上面的评论,Pillow 只是 PIL 的重新打包、更新版本,因为 PIL 的原始维护者很久以前就停止了它的工作。当你 pip install Pillow 时,你仍然将它作为 PIL 导入。在这种情况下,它们是相同的。

为了回答您的问题,枕头安装说明提到:

Pillow >= 2.1.0 不再支持import _imaging. 请from PIL.Image import core as _imaging改用。

我不确定你的代码在哪里导入_imaging,所以我认为你有几个选择:

  1. 使用旧版本的 Pillow (pre 2.1.0)
  2. 找到您要导入的位置_imaging并将其替换为更新的from PIL.Image import core as _imaging
  3. 更新到当前版本的 Pillow(请参阅下面的更新)

受此问题的启发,还有第四个选项是手动重定向导入。如果你不能做前三个之一,我只会这样做。把它放在你的代码中的某个地方,在你执行破坏事情的导入之前运行。您可能需要稍微调整一下才能使其正常工作:

from PIL.Image import core as _imaging
import sys
sys.modules['PIL._imaging'] = _imaging

稍后from PIL import _imaging现在应该真正导入新核心。

更新:

更新 Pillow 也可以解决问题。在 7.2.0 中,我可以_imaging以旧方式导入:

>>> import PIL
>>> from PIL import _imaging
>>> print(PIL.__version__)
7.2.0
>>> print(_imaging)
<module 'PIL._imaging' from '...\\lib\\site-packages\\PIL\\_imaging.cp37-win_amd64.pyd'>

推荐阅读