首页 > 解决方案 > 尝试在 AWS Lambda 中使用 Pillow 时无法导入名称“_imaging”

问题描述

我正在尝试制作使用 PIL 的 AWS Lambda 函数。因此,我在我的项目目录中安装了 PIL

pip install Pillow -t .

第一次在本地机器上运行时,它导致

ImportError: cannot import name '_imaging'

我虽然做错了什么,从项目目录中删除了目录并重新PIP安装。然后它起作用了。Pillow*PIL

不幸的是,当我将所有内容打包成 ZIP 并发布到 AWS 时,该功能再次开始失败

Traceback (most recent call last):
  File "/var/task/myfile.py", line 9, in lambda_handler
    from PIL import Image
  File "/var/task/PIL/Image.py", line 64, in <module>
    from . import _imaging as core
ImportError: cannot import name '_imaging'

此错误的确切原因是什么以及如何修复它?

以下是我的项目目录中的文件列表:

$ ls
bin                          chardet-3.0.4.dist-info  Pillow-5.2.0.dist-info     ThumbnailEnergent_Lambda.zip
certifi                      idna                     requests                   myfile.py
certifi-2018.4.16.dist-info  idna-2.7.dist-info       requests-2.19.1.dist-info  urllib3
chardet                      PIL                      tests                      urllib3-1.23.dist-info

标签: pythonamazon-web-servicespython-imaging-library

解决方案


我今天实际上遇到了这个问题,发现我的 Lambda 运行时语言是 python3.6,因为我使用的是从早期项目中复制的 Cloudformation 模板。问题是我使用 Python 3.7 为我的 zip 文件下载了 Pillow,并且 Pillow 用 Python 运行时命名了它的 _imaging C 模块文件。

为了解决这个问题,我只需将我的运行时语言从 Python 3.6 更改为 Python 3.7。因此,只需确保您的上传脚本和 Lambda 函数的 Python 版本完全相同。


推荐阅读