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


免責聲明!

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



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