背景:
示例:
toBeMonitored(genHelloWorld(),
10,
20)
def toBeMonitored(a, b, c):
varNames = inspect.stack().doParse()
print(varNames)
def genHelloWorld():
return "Hello World"
>20)\n
问题:有什么方法可以从堆栈或其他任何地方检索完整的字符串:
“ toBeMonitored(genHelloWorld(), 10 20)“
答案 0 :(得分:1)
这两个装饰器从函数内部获取信息并获取函数调用的全文(不精确到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)