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

Python cProfile模块在AWS Lambda中抛出NameError异常求助

解决AWS Lambda中cProfile的NameError问题

问题原因

cProfile.run()执行字符串形式的代码时,默认使用独立的空命名空间,无法访问当前lambda_handler或模块中的函数(如myfunc)和变量(如x、y),因此抛出NameError。

解决方案

方案1:使用runctx传入命名空间

通过cProfile.Profile的runctx方法,显式传入当前的全局和局部命名空间,让解析器能找到目标函数和变量:

import cProfile
import time

def myfunc(reps, sleeptime):
    for x in range(reps):
        print(f"rep {x}")
        time.sleep(sleeptime)
        
def lambda_handler(event, context):
    x = 3
    y = 0.25
    profiler = cProfile.Profile()
    profiler.runctx('myfunc(x, y)', globals(), locals())
    profiler.print_stats(sort="cumtime")

方案2:使用runcall直接调用函数(推荐)

这种方式无需构造字符串语句,直接传入函数和参数,更简洁且避免上下文解析问题:

import cProfile
import time

def myfunc(reps, sleeptime):
    for x in range(reps):
        print(f"rep {x}")
        time.sleep(sleeptime)
        
def lambda_handler(event, context):
    x = 3
    y = 0.25
    profiler = cProfile.Profile()
    profiler.runcall(myfunc, x, y)
    profiler.print_stats(sort="cumtime")

额外说明

Lambda的性能分析结果会输出到CloudWatch日志,你可以在Lambda监控面板的日志流中查看完整的性能数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:48:19