说我有一个Python文件提取信息
def ihavefile(): i = 1
def anotherfile(): pass
我想提取从文件中的所有功能,如ihavefile
和anotherfile
。我怎么做?我只是逐行阅读文件,也许写一个正则表达式或有更好的方法吗?
说我有一个Python文件提取信息
def ihavefile(): i = 1
def anotherfile(): pass
我想提取从文件中的所有功能,如ihavefile
和anotherfile
。我怎么做?我只是逐行阅读文件,也许写一个正则表达式或有更好的方法吗?
鉴于你例如:
from inspect import getmembers, isfunction, getsource
import your_module
print getmembers(your_module, isfunction)
# [('anotherfile', <function anotherfile at 0x028129B0>), ('ihavefile', <function ihavefile at 0x027F3570>)]
for name, func in getmembers(your_module, isfunction):
print getsource(func)
一个很好的解决方案。我正在学习一些东西 –
两条评论。 1)如果模块具有全局代码,则该代码将运行,这可能会产生副作用。 2)如果您事先不知道模块的名称,请使用importlib。 –
这是否包括在类中的方法,那拉姆达? – John
或函数内的函数? – ezod
@ezod closures =) – John