获取python中调用函数的源代码

获取python中调用函数的源代码,python,Python,出于调试目的,我想获取调用我的函数的函数的源代码。因此,在以下情况下: def调用函数: x=123 y=x+1 myfunc def myfunc: 调用_source=f 我想要一个函数f,这样调用_source就变成了字符串 x=123 y=x+1 myfunc 这样的功能存在吗?我猜这可能是有可能的,比如sys.\u current\u frames和inspect模块 输出: def caller(): called() x = 123 # Some examp

出于调试目的,我想获取调用我的函数的函数的源代码。因此,在以下情况下:

def调用函数: x=123 y=x+1 myfunc def myfunc: 调用_source=f 我想要一个函数f,这样调用_source就变成了字符串

x=123 y=x+1 myfunc 这样的功能存在吗?我猜这可能是有可能的,比如sys.\u current\u frames和inspect模块

输出:

def caller():
    called()
    x = 123     # Some example code
    y = x + 1

inspect.getsourceobject将对象作为参数,并以字符串形式返回源代码。

如何使用+?您需要以编程方式将源代码作为str对象?为什么不在您选择的文本编辑器中使用带有断点等的现代调试器呢?然后,您可以在前面的源代码中逐步完成调用堆栈。我投票赞成复制,但除此之外:不要编写自己的调试器,这通常是一个非常糟糕的主意,除非您有一些有意义的疯狂用例,或者您正在开发一个编辑器/IDE,但是我不希望你在这里问这些问题。我很感激你建议使用调试器。我为开发人员编写工具。我知道我在这里做什么,说得对。无论你的动机和背景如何,这个问题都是有效的。
In [1]: import inspect                                                          

In [2]: def calling_func(): 
   ...:     x = 123 
   ...:     y = x + 1 
   ...:     text = f() 
   ...:     print(text) 
   ...:                                                                         

In [3]: def f() -> str: 
   ...:     frame = inspect.currentframe() 
   ...:     frame = frame.f_back  # go up one in the stack 
   ...:     text = inspect.getsource(frame) 
   ...:     return text 
   ...:                                                                         

In [4]: calling_func()                                                          
def calling_func():
    x = 123
    y = x + 1
    text = f()
    print(text)
In [1]: import inspect                                                          

In [2]: def calling_func(): 
   ...:     x = 123 
   ...:     y = x + 1 
   ...:     text = f() 
   ...:     print(text) 
   ...:                                                                         

In [3]: def f() -> str: 
   ...:     frame = inspect.currentframe() 
   ...:     frame = frame.f_back  # go up one in the stack 
   ...:     text = inspect.getsource(frame) 
   ...:     return text 
   ...:                                                                         

In [4]: calling_func()                                                          
def calling_func():
    x = 123
    y = x + 1
    text = f()
    print(text)