如何使用检查从 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()
46732 次浏览

The caller's frame is one frame higher than the current frame. You can use inspect.currentframe().f_back to find the caller's frame. Then use inspect.getframeinfo to get the caller's filename and line number.

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)

I would suggest to use inspect.stack instead:

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()

If the caller is the main file, simply use sys.argv[0]

I published a wrapper for inspect with simple stackframe addressing covering the stack frame by a single parameter spos:

E.g. pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)

where spos=0 is the lib-function, spos=1 is the caller, spos=2 the caller-of-the-caller, etc.