cProfile for Python无法识别函数名称

Ben*_*Ben 20 python profiling cprofile

我在一个名为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)')
Run Code Online (Sandbox Code Playgroud)

当我运行此管理命令时,它会引发以下错误:

      exec cmd in globals, locals
     File "<string>", line 1, in <module>
     NameError: name 'send_email' is not defined
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?cProfile如何评估字符串(在全局/本地名称空间中查找函数名称)?

Rik*_*ggi 40

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

我建议你用runctx:

cProfile.runctx('send_email()', None, locals())
Run Code Online (Sandbox Code Playgroud)

官方文档:

cProfile.runctx(command, globals, locals, filename=None)
Run Code Online (Sandbox Code Playgroud)

此函数类似于run(),添加了参数以提供命令字符串的全局变量和本地字典.

  • 对我来说:cProfile.runctx('send_email()',globals(),locals(),filename = None) (2认同)