如何使用检查从 Python 中的被调用者获取调用者的信息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3711184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:22:13  来源:igfitidea点击:

How to use inspect to get the caller's info from callee in Python?

pythoninspect

提问by prosseek

I need to get the caller info (what file/what line) from callee. I learned that I can use inpect module for that for purposes, but not exactly how.

我需要从被调用者那里获取调用者信息(什么文件/什么行)。我了解到我可以为此目的使用 inpect 模块,但不完全是如何使用。

How to get those info with inspect? 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()

采纳答案by unutbu

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

调用者的帧比当前帧高一帧。您可以使用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)

回答by Dmitry K.

I would suggest to use inspect.stackinstead:

我建议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()

回答by Jacob Cohen

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

如果调用者是主文件,只需使用 sys.argv[0]

回答by acue

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

我发布了一个包装器,用于通过一个参数覆盖堆栈帧的简单堆栈帧寻址进行检查spos

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

例如 pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)

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

spos=0lib函数在哪里,spos=1是调用者,spos=2调用者的调用者等。