我如何获得Python函数的源代码? [英] How can I get the source code of a Python function?
本文介绍了我如何获得Python函数的源代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
def foo(arg1,arg2):
#用args做些什么
a = arg1 + arg2
return a
我可以得到该函数的名称使用 foo.func_name
。我如何以编程方式获取它的源代码,就像我在上面输入的内容一样?
inspect.getsource(foo)
可能有帮助: 如果 foo
被定义为: p>
def foo(arg1,arg2):
#使用args
a = arg1 + arg2
返回
然后:
import inspect
lines = inspect.getsource(foo)
print(lines)
返回:
def foo(arg1,arg2):
#用args
a = arg1 + arg2
返回a
但是我相信if该函数是从字符串,流或导入的f编译的从一个已编译的文件,然后你不能检索它的源代码。
Suppose I have a Python function as defined below:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
I can get the name of the function using foo.func_name
. How can I programmatically get its source code, as I typed above?
解决方案
If the function is from a source file available on the filesystem, then inspect.getsource(foo)
might be of help:
If foo
is defined as:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
Then:
import inspect
lines = inspect.getsource(foo)
print(lines)
Returns:
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屋!
查看全文