首页 > 解决方案 > 从堆栈中获取多行函数调用字符串

问题描述

背景:

例子:

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

标签: pythonpython-2.7

解决方案


这两个装饰器从函数内部获取信息并获取函数调用的全文(不是 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)

推荐阅读