2

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'

Edited by pythopian: n/a

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
1
Contributor
1
Reply
16
Views
8 Years
Discussion Span
Last Post by pythopian
1

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)

Edited by pythopian: n/a

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.