我需要从被调用者那里获取调用者信息(什么文件/什么行)。我了解到我可以使用检查模块来达到此目的,但不知道具体如何使用。
如何通过检查获得该信息?或者还有其他方式获取信息吗?
import inspect
print __file__
c=inspect.currentframe()
print c.f_lineno
def hello():
print inspect.stack
?? what file called me in what line?
hello()
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())
# ('/home/unutbu/pybin/test.py', 10, '<module>', ['hello()\n'], 0)
我建议使用
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()
我发布了一个用于检查的包装器,使用简单的堆栈帧寻址通过单个参数覆盖堆栈帧
spos
:
例如
pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)
其中
spos=0
是 lib 函数,spos=1
是调用者,spos=2
是调用者的调用者,等等。
如果调用者是主文件,只需使用sys.argv[0]