Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 645
Ben Avatar asked Jan 17 '12 20:01

Ben


People also ask

How do you use cProfile in Python?

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.

Which tool will Analyse the data collected by the Python profiler?

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.


1 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.

like image 82
Rik Poggi Avatar answered Sep 26 '22 00:09

Rik Poggi