在函数中使用python inspect模块,我想获得调用该函数的行的源代码.
因此,在以下情况下:
def fct1():
# Retrieve the line that called me and extract 'a'
return an object containing name='a'
a = fct1()
我想检索fct1中的字符串"a=fct1()"
到目前为止,我所能做的就是使用以下工具检索整个模块的代码:
code = inspect.getsource(sys._getframe().f_back)
请注意,fct1()可以在主模块中多次调用.
最后,我想要的是检索变量名"a",如果我能在fct1()中得到s="a=fct1()",这很容易:
a_name = s.split("=")[0].strip()