我需要从Callee获取呼叫者信息(什么文件/何处)。我了解到,我可以将Intect Module用于目的,但不是完全正确的。

如何通过检查获取这些信息?还是还有其他方法可以获取信息?

import inspect

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

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

hello()
有帮助吗?

解决方案

呼叫者的框架比当前框架高一个帧。您可以使用 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)

其他提示

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

我发布了一个包装器,用于检查,并通过一个参数覆盖堆栈框架的简单stackframe spos:

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

在哪里 spos=0 是lib功能, spos=1 是呼叫者, spos=2 呼叫者,等等。

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top