Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - if given file name using inspect to get list of methods in file

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
like image 436
Tampa Avatar asked Dec 06 '25 07:12

Tampa


1 Answers

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
like image 199
Ashwini Chaudhary Avatar answered Dec 11 '25 05:12

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!