AWS S3 Lambda Python脚本函数执行时报错AttributeError: module ‘PIL‘ has no attribute ‘,Image‘cannot import name '_imaging' from 'PIL'

背景

代码示例如下

import PIL
def add_image(self, tag, img, step):
    summary = Summary()
    bio = BytesIO()
 
    if type(img) == str:
        img = PIL.Image.open(img)
    elif type(img) == PIL.Image.Image:
        pass
    else:
        img = scipy.misc.toimage(img)

python脚本在本地可以执行,但是放到S3的Lambda中却总是报这个错

AttributeError: module ‘PIL‘ has no attribute ‘,Image‘cannot import name '_imaging' from 'PIL'

原因

原因是Lambda的Layer层,添加的脚本执行环境eve,打包压缩的zip包有问题,没有按照标准的解压流程去执行。

我一开始是直接把PIL和Pillow包直接压缩打成了一个zip包,这种就少了一些基础的执行环境依赖,标准的打包流程如下。

mkdir ~/create_layer
python3 -m venv create_layer

source create_layer/bin/activate
pip install pillow
deactivate

mkdir -p ~/pil/python
cd ~/pil
cp -r ~/create_layer/lib/python3.9/site-packages/* ./python/
zip -r pil.zip python

  

 

本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。

首发链接:https://www.cnblogs.com/lingyejun/p/18156503

 

参考链接

https://github.com/keithrozario/Klayers/issues/154

https://docs.aws.amazon.com/lambda/latest/dg/packaging-layers.html#packaging-layers-paths

https://docs.aws.amazon.com/lambda/latest/dg/python-layers.html#python-layer-packaging

posted @ 2024-04-24 22:13  翎野君  阅读(47)  评论(0编辑  收藏  举报