Supply a plugin interface
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Thu Apr 23 04:27:48 EDT 2009
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
More information about the Python-list
mailing list