python inspect.stack() 的简单使用


1.

复制代码
#python
# -*- encoding: utf-8 -*-
#获取函数的名字
import inspect
def debug():
    callnamer = inspect.stack()
    print('[debug] enter: {}'.format(callnamer))

debug()
复制代码

[debug] enter: [FrameInfo(frame=<frame object at 0x000000000096D448>, filename='E:/pythontest/sort.py', lineno=6, function='debug', code_context=[' callnamer = inspect.stack()\n'], index=0), FrameInfo(frame=<frame object at 0x00000000008F8828>, filename='E:/pythontest/sort.py', lineno=9, function='<module>', code_context=['debug()\n'], index=0)]

可以看出是一个列表

2.选取列表的第二项

复制代码
#python
# -*- encoding: utf-8 -*-
#获取函数的名字
import inspect
def debug():
    callnamer = inspect.stack()[1]
    print('[debug] enter: {}'.format(callnamer))

debug()
复制代码

[debug] enter: FrameInfo(frame=<frame object at 0x00000000004A8828>, filename='E:/pythontest/sort.py', lineno=9, function='<module>', code_context=['debug()\n'], index=0)

3.选取函数的名字

复制代码
#python
# -*- encoding: utf-8 -*-
#获取函数的名字
import inspect
def debug():
    callnamer = inspect.stack()[1][4]
    print('[debug] enter: {}'.format(callnamer))

debug()
复制代码

[debug] enter: ['debug()\n']


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM