4

I am trying to make AWS Lambda function, which uses PIL. Hence I installed PIL inside my project directory with

pip install Pillow -t .

First time it ran on local machine, it caused

ImportError: cannot import name '_imaging'

I though I did something wrong and deleted PIP and Pillow* directories from project directory and reinstalled PIL. Then it worked.

Unfortunately, when I packed everythong into ZIP and posted to AWS, the function started to fail with it again

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'

What is the exact reason of this error and how fix it?

Below are file list in my project dir:

$ 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
Dims
  • 47,675
  • 117
  • 331
  • 600
  • 1
    Did you find an answer to this? – Jack Mar 28 '19 at 15:58
  • Hey, I posted a solution here that does not require Docker. You just create a layer, the trick being that you have the correct version of Python locally, which you can install if needed. https://stackoverflow.com/a/74736780/1375627 – MattC Dec 08 '22 at 22:02

1 Answers1

4

I was actually having this issue today, and found that my Lambda runtime language was python3.6 because I was using a Cloudformation template I had copied from an earlier project. The problem was that I had downloaded Pillow using Python 3.7 for my zip file, and Pillow names its _imaging C module files with the Python runtime.

In order to fix this I just had to change my runtime language from Python 3.6 to Python 3.7. So just make sure the Python version is exactly the same for your upload script and your Lambda function.

Patrick
  • 41
  • 3