如何获取 Python 函数的源代码?
问题描述:
假设我有一个定义如下的 Python 函数:
Suppose I have a Python function as defined below:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
我可以使用 foo.func_name
获取函数的名称.我如何以编程方式获取其源代码,正如我在上面输入的那样?
I can get the name of the function using foo.func_name
. How can I programmatically get its source code, as I typed above?
答
如果函数来自文件系统上可用的源文件,则 inspect.getsource(foo)
可能有帮助:
If the function is from a source file available on the filesystem, then inspect.getsource(foo)
might be of help:
如果 foo
定义为:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
那么:
import inspect
lines = inspect.getsource(foo)
print(lines)
返回:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
但我相信,如果函数是从字符串、流编译或从编译文件导入的,那么您将无法检索其源代码.
But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.