为什么 'setprofile' 打印此
问题描述:
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()
call a 5 -> None#what is it
aaa
return a 6 -> None#what is it
return <module> 12 -> None#what is it
为什么打印此。
答
由于您在其上调用了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_call
和c_return
案件你应该 - 可能没有隐式的utf-8
转换在您的特定平台上打印(什么操作系统?什么级别的Python?什么IDE,如果有的话)。
答
这似乎也许你想知道为什么arg是无。 arg
对于每个事件具有不同的含义。对于“退货”,arg
是要返回的值。对于“例外”,它是异常信息的三倍。有关更多信息,请参见http://docs.python.org/library/sys.html#sys.settrace。
真正的问题是,你期望它打印什么? – 2010-01-11 00:57:23