Plug-Ins In A Python Application

Fredrik Lundh fredrik at pythonware.com
Tue Apr 18 14:33:27 EDT 2006


redefined.horizons at gmail.com wrote:

> Is it possible to load and use "modules" containing plug-in code
> written by third party developers into a running instance of the
> framework? How would I do this? Do I need to "dynamically load" the
> module at runtime? (I will scan a folder in the application direcotry
> for XML files containing information about the plug-ins, including the
> modules that implement them.)

a simple approach is to do something like

    for file in list_of_plugins:
        ns = {}
        execfile(file, ns)
        # pick up interesting objects from the namespace dictionary
        # e.g.
        callback = ns["callback"]

where individual plugins might look something like

    # my plugin

    def callback(event):
        pass # do something here

You can prepopulate the namespace to make application-specific
objects available for the plugins:

    context = MyContext()

    for file in list_of_plugins:
        ns = dict(context=context)
        execfile(file, ns)

which allows the plugins to do e.g.

    # my plugin

    def callback(event):
        pass

    context.register(callback)

or you can use a plugin initialization function:

    context = MyContext()

    for file in list_of_plugins:
        ns = {}
        execfile(file, ns)
        setup = ns["setup"]
        setup(context)

where the plugins look like:

    def callback(event):
        pass

    def setup(context):
        context.register(callback)

and so on.  To learn more about this, look up exec/execfile and
__import__ in the library reference.

</F>






More information about the Python-list mailing list