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

107 投票
4 回答
56512 浏览
提问于 2025-04-16 04:08

我需要从被调用的函数那里获取调用者的信息(比如是哪个文件、哪一行)。我了解到可以使用inspect模块来实现这个目的,但我不太清楚具体怎么做。

那么,怎么通过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()

4 个回答

2

我发布了一个叫做 inspect 的工具的封装,它可以通过一个简单的参数 spos 来处理堆栈帧。

比如,你可以这样使用:pysourceinfo.PySourceInfo.getCallerLinenumber(spos=1)

这里 spos=0 表示库函数本身,spos=1 表示调用这个函数的地方,spos=2 则是调用者的调用者,以此类推。

54

我建议你使用 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()
130

调用者的框架比当前框架高一个层级。你可以使用 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) 

撰写回答