I have a list of python files. I need to get all methods e.g. functions using inpect
E.g. mylist = ['/path/to/myfle.py']
/path/to/myfle.py
def foo():
return 'bar'
def bar():
return 'foo'
How do I get the list of methods if given a file name and path?
for file in mylist:
????
#The file exists
ls /home/ubuntu/workspace/ndkt-scraper/src/parsers/pacer/parser_pacer_file.py
/home/ubuntu/workspace/ndkt-scraper/src/parsers/pacer/parser_pacer_file.py
strs = '/home/ubuntu/workspace/ndkt-scraper/src/parsers/pacer/parser_pacer_file.py'
path, _ = os.path.splitext(strs) #now path is '/path/to/myfile'
file_name = path.split('/')[-1] # returns myfile]
mod = importlib.import_module(file_name, path)
Traceback (most recent call last):
File "/home/ubuntu/workspace/ndkt-scraper/src/crawler.py", line 31, in <module>
mod = importlib.import_module(file_name, path)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named parser_pacer_file
parser_pacer_file.py
def parser_pacer_method(html):
data = {'foo':'bar'}
return data
Use importlib to import a module using a path and then use types module to filter out functions from that imported module.
>>> import os
>>> import types
>>> import importlib
>>> strs = '/path/to/myfle.py'
>>> path, _ = os.path.splitext(strs) #now path is '/path/to/myfile'
>>> file_name = path.split('/')[-1] # returns myfile
>>> mod = importlib.import_module(file_name, path)
>>> funcs = [x for x in dir(mod) if isinstance(getattr(mod,x), types.FunctionType)]
>>> funcs
['foo', 'func'] #name of functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With