cProfile for Python does not recognize Function name

Question:

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

Asked By: Ben

||

Answers:

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.

Answered By: Rik Poggi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.