Python显示函数调用堆栈

网上找到如下几个思路:

1、用inspect模块

2、用sys._getframe模块

3、用sys.exc_traceback,先抛一个异常,然后抓出traceback

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

def test(depth = 0):
    frame = sys._getframe(depth)
    code = frame.f_code

    print "frame depth = ", depth
    print "func name = ", code.co_name
    print "func filename = ", code.co_filename
    print "func lineno = ", code.co_firstlineno
    print "func locals = ", frame.f_locals

def main():
    test(0)
    print "--------"
    test(1)

if __name__ == "__main__":
    main()

 

import inspect

class A:
  def a(self):
    print("A.a()")
    B().b()

class B:
  def b(self):
    print("B.b()")
    stack = inspect.stack()
    the_class = stack[1][0].f_locals["self"].__class__
    the_method = stack[1][0].f_code.co_name
    print("  I was called by {}.{}()".format(str(the_class), the_method))

A().a()

 

def currentframe():
    """Return the frame object for the caller's stack frame."""
    try:
        raise Exception
    except:
        return sys.exc_traceback.tb_frame.f_back

 

 

更多信息可参考:

http://stackoverflow.com/questions/11799290/get-function-callers-information-in-python

http://stackoverflow.com/questions/900392/getting-the-caller-function-name-inside-another-function-in-python

http://stackoverflow.com/questions/17065086/how-to-get-the-caller-class-name-inside-a-function-of-another-class-in-python

posted @ 2013-08-07 14:55  鸪斑兔  阅读(16143)  评论(1编辑  收藏  举报