一、介绍

inspect模块主要的四种用处:

1.对是否是模块、框架、函数等进行类型检测

2.获取源码

3.获取类或函数的参数信息

4.解析堆栈

二、使用

只写了2个自己用到的方法,方法太用,https://docs.python.org/3/library/inspect.html,可以看官方文档

#获取python函数参数的名称和默认值,返回一个命名的元组
inspect.getfullargspec(func) #返回调用者堆栈的帧记录列表,返回列表中的每一条为调用者,最后一条为堆栈上最外层的调用者
inspect.stack(context=1)
inspect.stack()的结果会随着调用层数的变化而变化
stack=inspect.stack()
print(stack)
#[FrameInfo(frame=<frame object at 0x000001F3A7201C88>,
# filename='D:/PycharmProjects/flask/flask_demo/app.py',
# lineno=34, function='<module>',
# code_context=['stack=inspect.stack()\n'], index=0)] def run():
stack=inspect.stack()
print(stack)
run()
# [FrameInfo(frame=<frame object at 0x0000019BD0706CA8>,
# filename='D:/PycharmProjects/flask/flask_demo/app.py',
# lineno=43, function='run',
# code_context=[' stack=inspect.stack()\n'], index=0),
# FrameInfo(frame=<frame object at 0x0000019BCE31FA48>,
# filename='D:/PycharmProjects/flask/flask_demo/app.py',
# lineno=50, function='<module>', code_context=['run()\n'], index=0)] def person():
def run():
stack=inspect.stack()
print(stack)
return run()
person()
# [FrameInfo(frame=<frame object at 0x0000017020FCE048>, filename='D:/PycharmProjects/flask/flask_demo/app.py', lineno=58, function='run', code_context=[' stack=inspect.stack()\n'], index=0),
# FrameInfo(frame=<frame object at 0x00000170202FB808>, filename='D:/PycharmProjects/flask/flask_demo/app.py', lineno=60, function='person', code_context=[' return run()\n'], index=0),
# FrameInfo(frame=<frame object at 0x000001701E06FA38>, filename='D:/PycharmProjects/flask/flask_demo/app.py', lineno=61, function='<module>', code_context=['person()\n'], index=0)]
import inspect

def func(name,phone,authcCde=""):
return name,phone,authcCde apiMethod=func
args = inspect.getfullargspec(apiMethod).args
print(args)
05-28 14:20