python 获取函数请求来源
Python 2023/10/11 11:46:49 点击:不统计
python怎么查询函数被调用是从哪里发起的,看下面代码实例。
使用了python 的内置 inspect
结果如下:
import inspect
class do():
def do_it(self):
caller = inspect.getframeinfo(inspect.currentframe().f_back)
print("I'm file:", inspect.getframeinfo(inspect.currentframe()).filename,
" Function:", inspect.getframeinfo(inspect.currentframe()).function)
# 输出调用当前函数信息
print("Call from file:", caller.filename,
"line no:", caller.lineno,
"Called from :", caller.function)
def call_do_something(self):
do_something()
def do_something():
caller = inspect.getframeinfo(inspect.currentframe().f_back)
# 输出当前函数信息
print("I'm file:", inspect.getframeinfo(inspect.currentframe()).filename,
" Function:", inspect.getframeinfo(inspect.currentframe()).function)
# 输出调用当前函数信息
print("Call from file:", caller.filename,
"line no:", caller.lineno,
"Called from :", caller.function)
def method_call():
do_something()
def class_call(obj):
obj.do_it()
if __name__ == "__main__":
method_call() # 这里是方法 调用方法
print("-----forasp 分割线---------")
Obj = do()
Obj.call_do_something() # 类 调用 外部方法
print("------forasp 分割线--------")
class_call(Obj) # 外部方法通过类 调用类方法
结果如下:
I'm file: /Python/main_class.py Function: do_something
Call from file: /Python/main_class.py line no: 36 Called from : method_call
--------------
I'm file: /Python/main_class.py Function: do_something
Call from file: /Python/main_class.py line no: 21 Called from : call_do_something
--------------
I'm file: /Python/main_class.py Function: do_it
Call from file: /Python/main_class.py line no: 40 Called from : class_call
转载%77%77%77请%2E%66%6F%72%61%73%70%2E%63%6E注明
·上一篇:python __call__ >> ·下一篇:python 读取excel sheet 内容 >>