我想知道是否我們可以找出哪些函數調用另一個特定的函數?我們可以找出哪個函數在Python中調用我的目標函數嗎?
例如,
def f1(): print 1
def f2(): f1()
當我們執行這個腳本
>>> f2()
1
我們應該知道f2
叫我的目標f1
。那可能嗎?
我想知道是否我們可以找出哪些函數調用另一個特定的函數?我們可以找出哪個函數在Python中調用我的目標函數嗎?
例如,
def f1(): print 1
def f2(): f1()
當我們執行這個腳本
>>> f2()
1
我們應該知道f2
叫我的目標f1
。那可能嗎?
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
>>>
我想你想要做的是做一個堆棧跟蹤。這可以通過調用
traceback.print_exc()
你當然需要導入回溯。
可以使用模塊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()
[email protected]:~/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
可以在調用函數作爲參數傳遞給該函數。 類似於: def f2(f2) –
爲什麼你需要知道這個?如果函數需要表現不同,應該有一個參數告訴它該做什麼,它不應該從哪個函數中調用它。 – Barmar
嘗試此線程:http://stackoverflow.com/questions/2529859/get-parent-function Hopefuly它會有所幫助! –