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)?
The syntax is cProfile. run(statement, filename=None, sort=-1) . You can pass python code or a function name that you want to profile as a string to the statement argument. If you want to save the output in a file, it can be passed to the filename argument.
Analysis of the profiler data is done using the Stats class. This class constructor creates an instance of a “statistics object” from a filename (or list of filenames) or from a Profile instance.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With