Supply a plugin interface

Almar Klein almar.klein at gmail.com
Thu Apr 23 05:59:56 EDT 2009


Hi,

I did this a few times and put the code that loads the plugins in
the __init__.py of the plugin directory. You then do not have to
do the path stuff.

You can also make a rule that the class defined in each
plugin module should be a certain name, for example the same
name as the module (but starting with a capital to follow pep8).

Cheers,
  Almar


2009/4/23 Steven D'Aprano <steven at remove.this.cybersource.com.au>

> On Thu, 23 Apr 2009 09:47:56 +0200, Johannes Bauer wrote:
>
> > Hello group,
> >
> > I'm developing a GUI application in Python and having a blast so far :-)
> >
> > What I'd like to add: I want the GUI users to supply plugin scripts,
> > i.e. offer some kind of API. That is, I want the user to write short
> > Python pieces which look something like
> >
> > import guiapp
> >
> > class myplugin():
> >       def __init__(self):
> >               guiapp.add_menu("foobar")
> >
> >       def exec(self, param):
> >               print("foo")
>
> "exec" is a reserved word:
>
> >>> def exec(self, param):
>  File "<stdin>", line 1
>    def exec(self, param):
>           ^
> SyntaxError: invalid syntax
>
>
> > the GUI application should now browse the plugin directory and read
> > those plugin python files and somehow incorporate (i.e. discover what
> > modules are there, instanciate, etc.)
> >
> > How do I do that at runtime with Python?
>
> Untested:
>
> import os
> import sys
> plugin_dir = os.path.expanduser('~/some/path/')
> plugins = set()
> for name in os.listdir(plugin_dir):
>    base, ext = os.path.splitext(name)
>    if ext in ('.py', '.pyc', '.pyo'):
>        plugins.add(base)
> save_path = sys.path
> plugin_modules = []
> try:
>    sys.path = [plugin_dir]
>    for name in plugins:
>        plugin_modules.append(__import__(name))
> finally:
>    sys.path = save_path
>
>
>
>
> Hope this is useful.
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090423/337403c6/attachment-0001.html>


More information about the Python-list mailing list