在AWS Lambda中导入matplotlib遇NumPy依赖错误,求解决方案
解决AWS Lambda中NumPy导入错误问题
问题场景
我平时用JavaScript开发,刚接触AWS Python开发,尝试用matplotlib生成饼图并上传到S3,代码如下:
import json import matplotlib.pyplot as plt import numpy import random import boto3 def lambda_handler(event, context): # 生成饼图随机数据 labels = ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5'] sizes = [random.randint(1, 10) for _ in range(len(labels))] colors = ['red', 'blue', 'green', 'orange', 'purple'] # 创建饼图 plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%') plt.title('Random Pie Chart') # 将图表保存到字节缓冲区 buffer = BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) # 上传图表到S3 s3 = boto3.client('s3') bucket_name = 'piechart_bucket' file_name = 'pie_chart.png' s3.upload_fileobj(buffer, bucket_name, file_name)
运行时出现ImportError,错误信息:
Runtime.ImportModuleError: Unable to import module 'lambda_function': IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.10 from "/var/lang/bin/python3.10" * The NumPy version is: "1.24.3" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: No module named 'numpy.core._multiarray_umath'
我添加依赖的操作步骤:
- 使用
pip install -t安装所有依赖 - 将依赖放入"python"文件夹
- 压缩该python文件夹
- 上传压缩包作为Layer并添加到函数中
运行环境为Python 3.10,matplotlib版本为3.3.4。
解决方案
1. 在兼容Lambda的环境中构建依赖
Lambda运行在Amazon Linux 2环境中,本地Windows/macOS直接安装的带C扩展依赖(比如NumPy)会存在兼容性问题,必须在匹配环境中构建:
- 使用Docker模拟Lambda环境安装依赖:
# 创建符合要求的目录结构 mkdir -p python/lib/python3.10/site-packages # 用Lambda官方镜像安装兼容版本的依赖 docker run -v "$PWD":/var/task public.ecr.aws/sam/build-python3.10:latest /bin/sh -c "pip install numpy==1.23.5 matplotlib==3.5.3 -t python/lib/python3.10/site-packages/; exit" - 压缩整个
python文件夹(注意:直接压缩文件夹本身,不要压缩内部内容,确保解压后路径为python/lib/python3.10/site-packages/)
2. 修正Layer的目录结构
Lambda Layer的Python依赖必须遵循python/lib/pythonX.X/site-packages/的目录结构,之前仅将依赖放在python文件夹根目录,会导致Lambda无法识别模块,按上面步骤构建后可自动符合要求。
3. 匹配依赖版本兼容性
- matplotlib 3.3.4不支持Python 3.10,需升级到3.5.0及以上版本
- NumPy 1.24.x和旧版matplotlib存在兼容冲突,降级到1.23.5可解决该问题
4. 修正代码中的缺失导入
原代码使用BytesIO但未导入,需添加:
from io import BytesIO
内容的提问来源于stack exchange,提问作者coolbeans
相关产品推荐
相关产品推荐

