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

AWS Lambda中Python模块导入报错Runtime.ImportModuleError的修复方法(无需使用EC2)

Fixing AWS Lambda Import Error for utils.py Module

Let's break down why you're hitting this error and how to fix it without extra resources like EC2:

Root Cause

Your local environment works because Python automatically adds your current working directory to sys.path, so it can find utils.py or common/utils.py regardless of how you import it. But AWS Lambda runs your code from the root of your deployment zip—and right now, your Terraform config is only packing file.py into the zip, not the entire common directory structure. That's why Lambda can't locate the utils or common.utils module.

Step-by-Step Fixes

1. Update Your Import Statement

First, use an absolute import in file.py that matches the eventual structure of your deployment zip:

from common.utils import hello

This ensures Lambda looks for the common directory (at the zip root) and imports hello from utils.py inside it.

2. Fix Terraform's Archive Configuration

Instead of packing just a single file.py, you need to pack the entire src directory (which should contain file.py and the common subdirectory). Replace your existing archive_file data source with this:

data "archive_file" "file_zip" {
  type              = "zip"
  source_dir        = "${path.module}/src"  # Pack the entire src directory
  output_file_mode  = "0666"
  output_path       = "${path.module}/bin/file.zip"
  
  # Optional: Exclude unnecessary files/folders to keep the zip lean
  excludes          = ["__pycache__/*", ".DS_Store"]
}

This will create a zip with the correct structure:

file.zip/
├── file.py
└── common/
    └── utils.py

3. Verify the Deployment Package

After generating the zip, unzip it locally to confirm the structure matches the example above. This is a quick way to catch any packing issues before deploying to Lambda.

4. Double-Check Lambda Handler Configuration

Make sure your Lambda function's handler is set correctly. If your handler function is named lambda_handler inside file.py, the handler value should be:

file.lambda_handler

This tells Lambda to look for file.py at the root of the zip and execute the lambda_handler function.

Why This Works

By packing the entire directory structure, you're replicating your local project layout in Lambda's runtime environment. The absolute import ensures Python can resolve the module path correctly from the zip's root directory.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 02:22:27