33

我在一个名为电子邮件的应用程序中有一个功能,我想对其进行分析。当我尝试做这样的事情时,它会爆炸

   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 如何评估字符串(在全局/本地命名空间中查找函数名称)?

4

1 回答 1

61

问题是您send_email在方法定义中导入。

我建议你使用runctx

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

官方文档

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

此函数类似于 run(),添加了参数来为命令字符串提供全局和局部字典。

于 2012-01-17T20:46:52.610 回答