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

2024-04-26 21:48:54 发布

您现在位置:Python中文网/ 问答频道 /正文

背景:

  • 出于证明原因,我必须提取被调用函数的参数名称
  • 由于公司的编码准则,函数被编码为多行

示例:

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


Tags: 函数名称证明示例编码参数def公司
1条回答
网友
1楼 · 发布于 2024-04-26 21:48:54

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

相关问题 更多 >