You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda部署后Python包pytest无法找到问题排查

我的操作步骤

  • 通过 sam init --runtime <runtime> --name <project-name> 创建AWS标准的hello_world示例代码
  • 将 pytest 添加到requirements.txt中,并在 app.py 里加入了 import pytest 语句
  • 执行命令 sam build --template-file template.yaml && sam deploy --template-file template.yaml --config-env dev --profile awsprofile 完成构建和部署

遇到的问题

在AWS上运行函数时,导入 pytest 失败,提示该包不存在。

备注

  • 本地的 .aws-sam/build 文件夹中已包含pytest包,符合预期。

可能的原因及解决方向

  1. 部署未使用构建后的模板
    你在sam deploy时指定了原始的template.yaml,而非构建后生成的.aws-sam/build/template.yaml。原始模板没有包含构建好的依赖包路径配置,Lambda无法加载到pytest。
    解决:将sam deploy的--template-file参数改为.aws-sam/build/template.yaml,或直接省略该参数,SAM会默认使用构建后的模板。

  2. 构建环境与Lambda运行时不匹配
    若本地构建环境(操作系统、Python版本)和Lambda运行时不一致,会导致依赖包兼容性问题。比如本地用Windows构建,Lambda是Linux环境,即使build文件夹里有pytest,部署后也无法识别。
    解决:使用sam build --use-container参数在容器中构建,确保依赖包适配Lambda环境:

    sam build --template-file template.yaml --use-container && sam deploy --config-env dev --profile awsprofile
    
  3. pytest版本与Lambda运行时不兼容
    requirements.txt中未指定pytest版本,可能安装了与Lambda运行时不兼容的版本,导致部署后无法正常导入。
    解决:在requirements.txt中指定兼容的pytest版本,比如pytest==7.4.0(根据你的Python运行时选择对应版本),重新构建部署。

  4. SAM构建过程存在静默错误
    构建时可能出现未提示的错误,导致依赖包未完整打包到部署包中。
    解决:删除.aws-sam文件夹,重新执行sam build,查看构建日志确认是否有报错,确保依赖包正常安装。

内容的提问来源于stack exchange,提问作者DarkTrick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:04:55