2010-09-14 162 views
62

我需要從被調用者那裏獲得調用者信息(什麼文件/什麼行)。我瞭解到我可以使用模塊來達到目的,但不完全如此。如何使用inspect從Python中的被調用者獲取調用者的信息?

如何通過檢查獲得這些信息?或者有沒有其他的方式來獲取信息?

import inspect 

print __file__ 
c=inspect.currentframe() 
print c.f_lineno 

def hello(): 
    print inspect.stack 
    ?? what file called me in what line? 

hello() 

回答

67

調用者的幀比當前幀高一幀。您可以使用inspect.currentframe().f_back來查找呼叫者的框架。 然後使用inspect.getframeinfo來獲取調用者的文件名和行號。

import inspect 

def hello(): 
    previous_frame = inspect.currentframe().f_back 
    (filename, line_number, 
    function_name, lines, index) = inspect.getframeinfo(previous_frame) 
    return (filename, line_number, function_name, lines, index) 

print(hello()) 

# (<frame object at 0x8ba7254>, '/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0) 
+0

感謝您的回答。我如何獲得來電者的來電者? – prosseek 2010-09-14 17:31:52

+4

@prosseek:要獲得調用者的調用者,只需將索引'[1]'更改爲'[2]'。 ('inspect.getouterframes'返回一個幀列表...)。 Python是精美的組織。 – unutbu 2010-09-14 17:38:07

+3

您也可以使用inspect.currentframe()。f_back。 – yoyo 2015-07-29 16:26:46

36

我會建議使用inspect.stack代替:

import inspect 

def hello(): 
    frame,filename,line_number,function_name,lines,index = inspect.stack()[1] 
    print(frame,filename,line_number,function_name,lines,index) 
hello() 
+0

它比使用@unutbu建議的'getouterframes'更好嗎? – ixe013 2014-09-04 03:02:35

+7

它更緊湊,更好地反映了意圖。 – 2014-09-04 08:40:02

+0

請注意''getouterframes(currentframe())''和'stack()'在https://github.com/python/cpython/blob/master/Lib/inspect.py#L1442 – ubershmekel 2016-05-12 21:14:52

-4

如果來電者是主要的文件,只需使用sys.argv中[0]

相關問題