如何在Python中使用inspect从被调用者那里获取调用者的信息?

问题描述 投票:0回答:4

我需要从被调用者那里获取调用者信息(什么文件/什么行)。我了解到我可以使用检查模块来达到此目的,但不知道具体如何使用。

如何通过检查获得该信息?或者还有其他方式获取信息吗?

import inspect

print __file__
c=inspect.currentframe()
print c.f_lineno

def hello():
    print inspect.stack
    ?? what file called me in what line?

hello()
python inspect
4个回答
128
投票

调用者的帧比当前帧高一帧。您可以使用

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) 

53
投票

我建议使用

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

2
投票

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

spos

例如

pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)

其中

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


-10
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.