Start New Discussion within our Software Development Community

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'
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

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)
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.