2012-01-17 24 views
13

我有一個應用程序中的函數稱爲電子郵件,我想配置文件。當我嘗試做這樣的事情,它炸燬Python的cProfile無法識別函數名稱

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如何評估字符串(在全局/本地命名空間中查找func名稱)?

回答

22

問題是您在方法定義中導入了send_email

我建議你使用runctx

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

the official documentation

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

此功能類似於運行(),與添加參數提供了全局變量和當地人詞典命令字符串。

+0

謝謝Rik,這個工作非常有效。 – Ben 2012-01-17 22:38:26