我想知道我们是否可以找出哪些函数调用另一个特定函数?
例如,
def f1(): print 1
def f2(): f1()
执行此脚本时
>>> f2()
1
我们应该知道f2
致电我的目标f1
。这可能吗?
答案 0 :(得分:0)
inspect.getframeinfo和其他相关功能可以提供帮助:
>>> import inspect
>>> def f1(): f2()
...
>>> def f2():
... curframe = inspect.currentframe()
... calframe = inspect.getouterframes(curframe, 2)
... print 'caller name:', calframe[1][3]
...
>>> f1()
caller name: f1
>>>
答案 1 :(得分:0)
我认为你想要做的是做一个堆栈跟踪。这可以通过调用
来实现traceback.print_exc()
你当然需要导入追溯。
答案 2 :(得分:0)
您可以使用模块traceback
def f():
pass
import traceback
traceback.print_stack()
print "Still working just fine"
pass
def caller():
f()
caller()
产量
File "traceback.py", line 12, in <module>
caller()
File "traceback.py", line 9, in caller
f()
File "traceback.py", line 4, in f
traceback.print_stack()
makarchuk@makarchuk:~/Workspace$ python2 traceback.py
File "traceback.py", line 13, in <module>
caller()
File "traceback.py", line 10, in caller
f()
File "traceback.py", line 4, in f
traceback.print_stack()
Still working just fine