如何获取 Python 函数的源代码? [英] How can I get the source code of a Python function?
本文介绍了如何获取 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.
这篇关于如何获取 Python 函数的源代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文