从堆栈获取多行函数调用的字符串

时间:2019-02-01 09:35:26

标签: python python-2.7

背景:

  • 出于证明的原因,我必须提取一个被调用函数的参数名。
  • 根据公司的编码准则,对功能进行了多行编码

示例:

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)“

1 个答案:

答案 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)