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

pythopian 2 Tallied Votes 684 Views Share

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
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 meeting, learning, and sharing knowledge.