如何使用检查从 Python 中的被调用者获取调用者的信息? [英] How to use inspect to get the caller's info from callee in Python?

查看:139
本文介绍了如何使用检查从 Python 中的被调用者获取调用者的信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

如何通过inspect获取这些信息?或者有什么其他方法可以获取信息?

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

推荐答案

调用者的帧比当前帧高一帧.您可以使用 inspect.currentframe().f_back 找到调用者的框架.然后使用 inspect.getframeinfo 获取调用者的文件名和行号.

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

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)

这篇关于如何使用检查从 Python 中的被调用者获取调用者的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆