Search code examples
pythonprofilingcprofile

cProfile for Python does not recognize Function name


I have a function in an app called email which I want to profile. When I try to do something like this, it blows up

   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)')

When I run this management command, it throws the following error:

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

What am I missing here? How does cProfile evaluate the string (look up func names in the global/local namespace)?


Solution

  • The problem is that you imported send_email inside your method definition.

    I suggest you to use runctx:

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

    From the official documentation:

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

    This function is similar to run(), with added arguments to supply the globals and locals dictionaries for the command string.