Python的cProfile无法识别函数名称。

37

我有一个位于名为“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()类似,但添加了参数来提供用于命令字符串的全局和本地字典。


10
针对我的情况: cProfile.runctx('send_email()', globals(), locals(), filename=None)翻译为:使用 cProfile.runctx('send_email()', globals(), locals(), filename=None) 来分析我的代码性能。 - Oliver Wilken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接