2012-11-02 121 views
2

說我有一個Python文件提取信息

def ihavefile(): i = 1 
def anotherfile(): pass 

我想提取從文件中的所有功能,如ihavefileanotherfile。我怎麼做?我只是逐行閱讀文件,也許寫一個正則表達式或有更好的方法嗎?

+2

這是否包括在類中的方法,那拉姆達? – John

+1

或函數內的函數? – ezod

+0

@ezod closures =) – John

回答

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) 
+0

一個很好的解決方案。我正在學習一些東西 –

+0

兩條評論。 1)如果模塊具有全局代碼,則該代碼將運行,這可能會產生副作用。 2)如果您事先不知道模塊的名稱,請使用importlib。 –