Really Simple PlugIns Loader - Import all modules in a folder in one swoop

pythopian

PlugIns in their simplest form can be just python modules that are dropped into some designated directory and dynamically loaded by the main application. This snippet can be used to do just that.

Usage

To load plugin modules:

>>> plugins = importPluginModulesIn('mypackage')
>>> plugins
{'foo': <module 'foo' from 'mypackage\foo.py'>, 'bar': <module 'bar' from 'mypackage\bar.py'>}

To access a plugin attribute or method:

>>> plugins['foo'].__name__
'foo'
476 Views
About the Author

Master's Degree in CS; Major in Automation Technology and Cybernetics; Passionate Pythoneer from the early days of Python; Former C++ nerd, but now clean.

import glob, imp
from os.path import join, basename, splitext

def importPluginModulesIn(directory):
    modules = {}
    for path in glob.glob(join(directory,'[!_]*.py')): # list .py files not starting with '_'
        name, ext = splitext(basename(path))
        modules[name] = imp.load_source(name, path)
    return modules
pythopian 10 Junior Poster in Training

Better yet:

import glob, imp
from os.path import join, basename, splitext

def importPluginModulesIn(dir):
    return dict( _load(path) for path in glob.glob(join(dir,'[!_]*.py')) )

def _load(path):
    name, ext = splitext(basename(path))
    return name, imp.load_source(name, path)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.