python 获取函数调用者

时间:2022-10-01 18:02:03
import traceback

def _mode():
    print "hi---------------------------"
    print traceback.extract_stack()[-2][2]

def fun1():
    _mode()

def fun2():
    _mode()


if __name__ == '__main__':
    fun2()
    fun1()
 
 
traceback.extract_stack() output>
 
[('test_traceback.py', 16, '<module>', 'fun1()'), ('test_traceback.py', 8, 'fun1', '_mode()'), ('test_traceback.py', 5, '_mode', 'print traceback.extract_stack()')]

 

 
 
  由三个数组组成list,我们只需要取[-2][2]即可。