Skip to content

Instantly share code, notes, and snippets.

@sapamja
Created August 17, 2014 19:48
Show Gist options
  • Save sapamja/33a1ab51c445302bbfb1 to your computer and use it in GitHub Desktop.
Save sapamja/33a1ab51c445302bbfb1 to your computer and use it in GitHub Desktop.
Load all module from path
import os
import sys
import importlib
import inspect
import logging
def load_module(module_path, filename):
""" returns the module if filename is a module else None """
if filename.endswith('.py'):
module = filename[:-3]
elif os.path.exists(os.path.join(module_path, filename, '__init__.py')):
module = filename
else:
return None
try:
return importlib.import_module(module)
except:
logging.exception('Loading %s failed.' % module)
return None
class PluginManager(object):
def __init__(self):
self.modules = {}
self.classes = {}
def add_path(self, module_path):
sys.path.append(module_path)
for filename in os.listdir(module_path):
module = load_module(module_path, filename)
if module:
self.modules[module.__name__] = module
self._extract_classes(module)
sys.path.remove(module_path)
def _extract_classes(self, module):
for name in dir(module):
obj = getattr(module, name)
if inspect.isclass(obj):
if hasattr(obj, '_VERSION'):
version = getattr(obj, '_VERSION')
logging.info("Found %s.%s %s" % (module.__name__, name, version))
self.classes[name] = obj
logging.getLogger().level = logging.INFO
plugins = PluginManager()
plugins.add_path('/home/test/multitool')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment