python frame 對象

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 "  funname   = %s()" % frame.f_code.co_name
    print "  file/line = %s:%s" % (frame.f_code.e, frame.f_lineno)

one()

Outputpython

<frame object at 0x606c50>
  #返回當前stack frame
  frame     = sys._getframe(0)
  funname   = three()
  file/line = stack.py:12
<frame object at 0x180be10>
  #返回當前stack 的上層stack frame 
  frame     = sys._getframe(1)
  funname   = two()
  file/line = stack.py:7
<frame object at 0x608d30>
  frame     = sys._getframe(2)
  funname   = one()
  file/line = stack.py:4

sys._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.ui

frameobject 屬性code

f_back -> frameobject對象

f_builtins -> dict key:python的內置函數名three

f_code -> 代碼對象get

def test():
    pass

print dir(test)

test.func_code #便是code object

f_globals -> dict 全局對象 能夠修改全局對象io

f_locals -> dict 同上test

f_linenoimport

經過pdb inspect current frame

import sys, pdb

def test():
    frame = sys._current_frames()
    a = "lmy"
    pdb.set_trace()

def aFunction():
    a = 1
    b = 'hello'
    c = (12, 3.45)
    test()
    d = "This won't show up in the frame"

aFunction()
相關文章
相關標籤/搜索