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 #當前行號

 例:

 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 -> 代碼對象

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM