说我有一个python文件
def ihavefile(): i = 1
def anotherfile(): pass
我想从文件中提取所有功能,例如ihavefile
和anotherfile
。我怎么做?我是否只是逐行阅读文件,也许写一个正则表达式或者有更好的方法吗?
答案 0 :(得分:4)
鉴于你的例子:
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)