2010-09-14 157 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]

相关问题