【问题标题】:cProfile for Python does not recognize Function namePython 的 cProfile 无法识别函数名称
【发布时间】:2012-02-12 15:03:13
【问题描述】:

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

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

【问题讨论】:

    标签: python profiling cprofile


    【解决方案1】:

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

    我建议你使用runctx:

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

    来自the official documentation

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

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

    【讨论】:

    • 对我来说:cProfile.runctx('send_email()', globals(), locals(), filename=None)
    猜你喜欢
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2018-03-26
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多