cProfile在Python中无法识别函数名称

37 投票
1 回答
14737 浏览
提问于 2025-04-17 10:28

我在一个叫做email的应用里有一个函数,我想对它进行性能分析。可是当我尝试这样做的时候,就出错了。

   from django.core.management import BaseCommand
   import cProfile


  class Command(BaseCommand):
       def handle(self, *args, **options):
           from email.modname import send_email
           cProfile.run('send_email(user_id=1, city_id=4)')

当我运行这个管理命令时,它出现了以下错误:

      exec cmd in globals, locals
     File "<string>", line 1, in <module>
     NameError: name 'send_email' is not defined

我这里漏掉了什么呢?cProfile是怎么处理这个字符串的(它是如何在全局或局部命名空间中查找函数名的)?

1 个回答

66

问题在于你在方法定义内部导入了 send_email

我建议你使用 runctx

cProfile.runctx('send_email()', None, locals())

来自 官方文档

cProfile.runctx(command, globals, locals, filename=None)

这个函数和 run() 类似,但多了参数,可以为命令字符串提供全局和局部的字典。

撰写回答