python获取函数地址,在python中获取函数调用者的信息

在Python中,可以使用sys._getframe()函数结合inspect模块来获取当前执行堆栈中的帧信息,从而得知特定函数的调用者。通过检查frame对象的f_code.co_name和f_locals属性,可以确定调用函数及其所在类。注意,sys._getframe()返回的是帧对象,可以通过f_back遍历整个堆栈。此外,inspect.stack()函数也能提供包含更多信息的帧列表。
摘要由CSDN通过智能技术生成

I want to get information about the callers of a specific function in python. For example:

class SomeClass():

def __init__(self, x):

self.x = x

def caller(self):

return special_func(self.x)

def special_func(x):

print "My caller is the 'caller' function in an 'SomeClass' class."

Is it possible with python?

解决方案

Yes, the sys._getframe() function let's you retrieve frames from the current execution stack, which you can then inspect with the methods and documentation found in the inspect module; you'll be looking for specific locals in the f_locals attribute, as well as for the f_code information:

import sys

def special_func(x):

callingframe = sys._getframe(1)

print 'My caller is the %r function in a %r class' % (

callingframe.f_code.co_name,

callingframe.f_locals['self'].__class__.__name__)

Note that you'll need to take some care to detect what kind of information you find in each frame.

sys._getframe() returns a frame object, you can chain through the whole stack by following the f_back reference on each. Or you can use the inspect.stack() function to produce a lists of frames with additional information.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值