Skip to content

Instantly share code, notes, and snippets.

@sapamja
Created August 17, 2014 19:48
Show Gist options
  • Select an option

  • Save sapamja/33a1ab51c445302bbfb1 to your computer and use it in GitHub Desktop.

Select an option

Save sapamja/33a1ab51c445302bbfb1 to your computer and use it in GitHub Desktop.

Revisions

  1. sapamja created this gist Aug 17, 2014.
    46 changes: 46 additions & 0 deletions load_module.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    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')