python - 从堆栈中获取多行函数调用字符串
问题描述
背景:
- 出于证明的原因,我必须提取被调用函数的参数名。
- 由于公司的编码指南,函数调用可能会被多行编码
例子:
toBeMonitored(genHelloWorld(),
10,
20)
def toBeMonitored(a, b, c):
varNames = inspect.stack().doParse()
print(varNames)
def genHelloWorld():
return "Hello World"
>20)\n
问题:有没有办法从堆栈或其他任何地方检索完整的字符串:
“待监控(genHelloWorld(),10, 20)”
解决方案
这两个装饰器从函数内部获取信息并获取函数调用的全文(不是 100% 精确,基于函数名出现):
import inspect
def inspect_inside(func): #Inspect from function
def wrapper(*args, **kwargs):
print('Function:', func.__name__)
argnames = inspect.getargspec(func).args
for i,k in enumerate(args):
print(argnames[i],'=',k)
for k in kwargs:
print(k,'=',kwargs[k])
return func(*args, **kwargs)
return wrapper
def inspect_outside(func): #Getting place of function call
def wrapper(*args, **kwargs):
frame = inspect.currentframe()
try:
filename = frame.f_back.f_code.co_filename
lineno = frame.f_back.f_lineno
with open(filename) as f:
filelines = f.readlines()
caller_text = ""
for i in range(lineno-1,0,-1):
caller_text = filelines[i] + caller_text
if filelines[i].find(func.__name__) >= 0:
break
print(caller_text)
finally:
del frame
return func(*args, **kwargs)
return wrapper
@inspect_inside
def toBeMonitored(a,b,c):
...
toBeMonitored("Hello World",
10,
20)
@inspect_outside
def toBeMonitored(a,b,c):
...
toBeMonitored("Hello World",
10,
20)
结果:
Function: toBeMonitored
a = Hello World
b = 10
c = 20
toBeMonitored("Hello World",
10,
20)
推荐阅读
- javascript - 如何在 React 的功能组件中制作与 componentDidUpdate 功能类似的功能?
- python - 如何在 Windows 中使用 pynput 按下媒体键?
- c++ - 简化静态成员函数调用的方法?
- c++ - 如何根据用户输入进行“加权”随机数生成,使某些数字优于其他数字?
- datastage - 从特定范围打印日期
- python - 熊猫没有从使用“\”的路径读取多个 Excel 文件
- javascript - 使用未在 Laravel 上更新的复选框进行 Ajax DB 更新
- docker - 在不使用“--net host”选项的情况下接收 docker 容器内的 UDP 多播数据包
- c++ - 每当我运行这个程序 C++ 时都会出错。我做错了什么
- javascript - 使用 image-size 检索图像尺寸,并将这些值添加到对象