_getframe([depth]) -> frameobject
Return a frame object from the call stack. If optional integer depth is
given, return the frame object that many calls below the top of the stack.
If that is deeper than the call stack, ValueError is raised. The default
for depth is zero, returning the frame at the top of the call stack.
This function should be used for internal and specialized
purposes only.
sys._getframe() 可以用来获取调用栈的帧对象,默认返回栈顶帧;如果指定depth,可以获取特定的帧。
示例:
def test(): classLocals = sys._getframe(1) for k in dir(classLocals): print k print "classLocals.f_locals is %s", type(classLocals.f_locals) for k, v in classLocals.f_locals.items(): print k, v if __name__ == "__main__": test()
输出:
__class__ __delattr__ __doc__ __format__ __getattribute__ __hash__ __init__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __sizeof__ __str__ __subclasshook__ f_back f_builtins f_code f_exc_traceback f_exc_type f_exc_value f_globals f_lasti f_lineno f_locals f_restricted f_trace classLocals.f_locals is %s <type 'dict'> __builtins__ <module '__builtin__' (built-in)> __file__ D:/code/jiehua/playground/main.py __package__ None sys <module 'sys' (built-in)> json <module 'json' from 'C:\Python27\lib\json\__init__.pyc'> time <module 'time' (built-in)> test <function test at 0x0000000006238978> __name__ __main__ requests <module 'requests' from 'C:\Python27\lib\site-packages\requests\__init__.pyc'> main <function main at 0x0000000005B2E668> __doc__ None
其中, f_locals 保存了当前帧的局部变量信息,我们也可以根据自己需求去修改
Add Comment