如何使用inspect来从python中获取调用者的信息?

pro*_*eek 72 python inspect

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

如何通过检查获得这些信息?或者有没有其他方法来获取信息?

import inspect

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

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

hello()
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 86

呼叫者的帧比当前帧高一帧.您可以使用它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)
Run Code Online (Sandbox Code Playgroud)

  • @prosseek:要获得调用者的调用者,只需将索引"[1]"更改为"[2]`.(`inspect.getouterframes`返回一个框架列表......).Python组织精美. (5认同)
  • 此代码示例有效,但性能很差。如果您只对单个帧而不是整个堆栈跟踪感兴趣,您可以获取前一帧并检查它的帧信息:```filename, line_number, clsname,lines, index = inspect.getframeinfo(sys. _getframe(1))``` (5认同)
  • 您还可以使用inspect.currentframe().f_back. (3认同)
  • @Mouscellaneous,这是一个巨大的节省,使我每次调用的时间从约 30 毫秒减少到约 4 毫秒。一个很好的功能是我可以这样做:`calling_function = inform.getframeinfo(sys._getframe(1))[2]`,这样我就不必因为我不关心的所有其他变量而浪费内存。我只是拉出调用函数名称 (3认同)
  • @JasonS:"堆栈框架中的文件名是[相对于启动目录](https://doughellmann.com/blog/2012/04/30/determining-the-name-of-a-process-from- python /)应用程序". (2认同)

Dmi*_* K. 43

我建议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()
Run Code Online (Sandbox Code Playgroud)

  • 它更紧凑,更能反映出意图. (8认同)
  • 我已经分析了我的代码,结果发现 `stack()` 比 `sys._getframe(1).f_lineno` 慢得多。在 1e6 调用中,它在我的 Linux 环境中增加了 10 分钟。 (3认同)