简体   繁体   中英

Extract information from Python file

Say I have a python file

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

I want to extract all the functions from the file, like ihavefile and anotherfile . How do I do that? Do I just read the file line by line and perhaps write a regex or is there a better way?

Given your example:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM