有没有办法找到什么函数称为当前函数?例如:
def first():
second()
def second():
# print out here what function called this one
有什么想法吗?
答案 0 :(得分:7)
import inspect
def first():
return second()
def second():
return inspect.getouterframes( inspect.currentframe() )[1]
first()[3] # 'first'
答案 1 :(得分:2)
您可以使用追溯模块的extract_stack功能。
import traceback
def first():
second()
def second():
print traceback.extract_stack(limit=2)[-2][2]
答案 2 :(得分:2)
答案 3 :(得分:1)
当您不想导入另一个模块时,这些可以很好地快速添加最小的调试辅助工具。 (仅限CPython,仅用于调试。)
def LINE( back = 0 ):
return sys._getframe( back + 1 ).f_lineno
def FILE( back = 0 ):
return sys._getframe( back + 1 ).f_code.co_filename
def FUNC( back = 0):
return sys._getframe( back + 1 ).f_code.co_name
def WHERE( back = 0 ):
frame = sys._getframe( back + 1 )
return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
frame.f_lineno, frame.f_code.co_name )
示例:
import sys, os # these you almost always have...
def WHERE( back = 0 ):
frame = sys._getframe( back + 1 )
return "%s/%s %s()" % ( os.path.basename( frame.f_code.co_filename ),
frame.f_lineno, frame.f_code.co_name )
def first():
second()
def second():
print WHERE()
print WHERE(1)
first()
输出:
$ python fs.py
fs.py/12 second()
fs.py/9 first()