How to iterate through a list of modules and call their methods in Python 3 -


goal: ability drop files "modules" folder & call common set of methods/vars each file.

should modules initialized static classes if of modules have common methods/vars?

my project folder tree:

/client     __init__.py      /modules         __init__.py         foo.py         bar.py         spam.py 

client __init__.py file:

from client.modules import __all__ modulestrings  (get list of "modules" "modulestrings") # how write function?  # initialize modules dynamically module in modules:     if (hasattr(module, 'init')):         print(module.__name__)         print("has initialize method!")         module.init()  # call do_stuff method in each module module in modules:     if (hasattr(module, 'do_stuff')):         print("has do_stuff method!")         module.do_stuff() 

modules __init__.py file:

# stores list of module string names in __all__ import os import glob files = glob.glob(os.path.dirname(__file__)+"/*.py") __all__ = [ os.path.basename(f)[:-3] f in files if "__init__" not in f] 

you may use native python "imp" module (https://docs.python.org/3.4/library/imp.html):

assuming same project tree:

/client __init__.py  /modules     __init__.py     foo.py     bar.py     spam.py 

client __init__.py file:

# -*- coding: utf-8 -*- #!/usr/bin/python  import modules.__init__ #here generate modules.__init__.__load_all__() 

modules __init__.py file:

# -*- coding: utf-8 -*- #!/usr/bin/python  import imp,os  def __load_all__(dir="modules"):     list_modules=os.listdir(dir)     list_modules.remove('__init__.py')     module_name in list_modules:         if module_name.split('.')[-1]=='py':             print "load module ' ",module_name,"' :"             foo = imp.load_source('module', dir+os.sep+module_name)             foo.myclass() 

and finally

modules (spam.py,bar.py, foo.py, etc...) file:

# -*- coding: utf-8 -*- #!/usr/bin/python  def __init__():     print "load"  def myclass():     print "myclass spam,bar,foo, etc..." 

when running client "init.py" , iterate through modules , initialize them dynamically.

best regards


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -