Python Frame

扫码查看

http://farmdev.com/src/secrets/framehack/index.html

sys._getframe([depth])

Return a frame object from the call stack
depth 表示调用栈的深度,默认为0,返回栈顶

def get_cur_info():
print sys._getframe().f_code.co_filename #当前文件名,可以通过__file__获得
print sys._getframe(0).f_code.co_name #当前函数名
print sys._getframe(1).f_code.co_name
#调用该函数的函数的名字,如果没有被调用,则返回<module>,貌似call stack的栈低
print sys._getframe().f_lineno #当前行号

例:

 import sys

 def one():
two() def two():
three() def three():
for num in range(3):
frame = sys._getframe(num)
show_frame(num, frame) def show_frame(num, frame):
print frame
print " frame = sys._getframe(%s)" % num
print " function = %s()" % frame.f_code.co_name
print " file/line = %s:%s" % (frame.f_code.co_filename, frame.f_lineno) one()

输出结果:

<frame object at 0x606c50>
frame = sys._getframe(0)
function = three()
file/line = stack.py:12
<frame object at 0x180be10>
frame = sys._getframe(1)
function = two()
file/line = stack.py:7
<frame object at 0x608d30>
frame = sys._getframe(2)
function = one()
file/line = stack.py:4

sys._getframe([depth]) -> frameobject

frameobject 属性

f_back -> frameobject

f_builtins -> dict key:python的内置函数名

f_code -> 代码对象

05-11 11:03
查看更多