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 #當前行號
例:
1 import sys 2 3 def one(): 4 two() 5 6 def two(): 7 three() 8 9 def three(): 10 for num in range(3): 11 frame = sys._getframe(num) 12 show_frame(num, frame) 13 14 def show_frame(num, frame): 15 print frame 16 print " frame = sys._getframe(%s)" % num 17 print " function = %s()" % frame.f_code.co_name 18 print " file/line = %s:%s" % (frame.f_code.co_filename, frame.f_lineno) 19 20 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 -> 程式碼物件