2010-01-11 138 views
0
import sys 
def a(): 
    print 'aaa' 
def profiler(frame, event, arg): 
    print event, frame.f_code.co_name, frame.f_lineno, "->", arg 

# profiler is activated on the next call, return, or exception 
sys.setprofile(profiler) 
a() 

打印爲什麼 'setprofile' 打印此

call a 5 -> None#what is it 
aaa 
return a 6 -> None#what is it 
return <module> 12 -> None#what is it 

爲什麼打印此。

+0

真正的問題是,你期望它打印什麼? – 2010-01-11 00:57:23

回答

3

由於您在其上調用了sys.setprofile,因此會在每個分析事件中調用profiler函數。

每次調用它時,都會打印一條線,因爲您將無條件的print語句作爲其主體。 爲什麼你做到了這一點,我們很難告訴你,讓你的「爲什麼」的問題真的,真的很奇特。

剖析事件只是調用和返回,每the docs

'call' 

一個函數被調用(或其他一些 代碼塊中輸入)。

'return' 

函數(或其他代碼塊)是 即將返回。

'c_call' 

C函數即將被調用。 這可能是一個擴展功能或內置的 。

'c_return' 

C函數已返回。

這是我在一個稍微簡單,更清晰的情況下,觀察什麼(Python的2.5或2.6,MacOSX的):

>>> def a(): 
...  print 'aaa' 
... 
>>> def profiler(frame, event, arg): 
...  print 'PROF %r %r' % (event, arg) 
... 
>>> sys.setprofile(profiler) 
PROF 'return' None 
>>> a() 
PROF 'call' None 
PROF 'c_call' <built-in function utf_8_decode> 
PROF 'c_return' <built-in function utf_8_decode> 
PROF 'return' (u'a()\n', 4) 
PROF 'call' None 
PROF 'call' None 
aaa 
PROF 'return' None 
PROF 'return' None 

不知道爲什麼你沒有看到c_callc_return案件你應該 - 可能沒有隱式的utf-8轉換在您的特定平臺上打印(什麼操作系統?什麼級別的Python?什麼IDE,如果有的話)。

0

這似乎也許你想知道爲什麼arg是無。 arg對於每個事件具有不同的含義。對於「退貨」,arg是要返回的值。對於「例外」,它是異常信息的三倍。有關更多信息,請參見http://docs.python.org/library/sys.html#sys.settrace