I was wondering if maybe we could figure out which functions call another specific function?
For example,
def f1(): print 1
def f2(): f1()
When we execute this script
>>> f2()
1
We should know f2
call my target f1
. Is that possible?
I was wondering if maybe we could figure out which functions call another specific function?
For example,
def f1(): print 1
def f2(): f1()
When we execute this script
>>> f2()
1
We should know f2
call my target f1
. Is that possible?
inspect.getframeinfo and other related functions in inspect can help:
>>> 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
>>>
What I think you want to do is to do a stack trace. This is possible by calling
traceback.print_exc()
Where you of course need to import traceback.
You can use module traceback
def f():
pass
import traceback
traceback.print_stack()
print "Still working just fine"
pass
def caller():
f()
caller()
yields
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