Best practices for dynamically loading plugins at startup

beza1e1 andreas.zwinkau at googlemail.com
Mon Sep 26 02:44:33 EDT 2005


I wrote this one:
--------------------------------------
def load_plugin(self, plugin, paths):
        import imp
        # check if we haven't loaded it already
        try:
            return sys.modules[plugin]
        except KeyError:
            pass
        # ok, the load it
        fp, filename, desc = imp.find_module(plugin, paths)
        try:
            mod = imp.load_module(plugin, fp, filename, desc)
        finally:
            if fp:
                fp.close()
        # instantiate and put into basket
        clazz = mod.main(self.config)
        if "input" in clazz.types:
            self.inputs.append(clazz)
        if "parser" in clazz.types:
            self.parser.append(clazz)
        if "output" in clazz.types:
            self.outputs.append(clazz)
--------------------------------------
The imp module is the key:
http://docs.python.org/lib/module-imp.html

The parameters for the load module function, are found by look through
the directory. So my plugins had a convention:
They have a class called main, which is initialized with one argument,
the config object.

That is quite a simple plugin system. You can check out the whole thing
here:
https://developer.berlios.de/projects/feedisto/




More information about the Python-list mailing list