如何在Python中使用inspect从被调用者那里获取调用者的信息?
我需要从被调用者那里获取调用者信息(什么文件/什么行)。我了解到我可以使用检查模块来达到此目的,但不知道具体如何使用。
您如何通过检查获得该信息?或者还有其他方式获取信息吗?
import inspect
print __file__
c=inspect.currentframe()
print c.f_lineno
def hello():
print inspect.stack
?? what file called me in what line?
hello()
I need to get the caller info (what file/what line) from the callee. I learned that I can use the inspect module for that purpose, but not exactly how.
How do you get that info with inspection? Or is there any other way to get the info?
import inspect
print __file__
c=inspect.currentframe()
print c.f_lineno
def hello():
print inspect.stack
?? what file called me in what line?
hello()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
调用者的帧比当前帧高一帧。您可以使用
inspect.currentframe().f_back
来查找调用者的框架。
然后使用 inspect.getframeinfo 获取调用者的文件名和行号。
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.
我建议使用
inspect.stack
代替:I would suggest to use
inspect.stack
instead:我发布了一个用于检查的包装器,使用简单的堆栈帧寻址通过单个参数
spos
覆盖堆栈帧:例如
pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)
其中
spos=0
是 lib 函数,spos=1
code> 是调用者,spos=2
是调用者的调用者,等等。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.如果调用者是主文件,只需使用 sys.argv[0]
If the caller is the main file, simply use sys.argv[0]