Python plugins

Tobias Klausmann klausman-un080902 at tuts.net
Sun Sep 8 06:13:00 EDT 2002


Hi there,

For an open source project that needs to be extensible by its
users, I would like to create a plugin architecture. Mind you,
I'm not trying to use Python as a plugin language only like XChat
or Gnumeric do. Let me illustrate:

I have a directory somewhere in PYTHONPATH (let's just assume
it's in the CWD) that contains lots and lots of *.py files with a
defined set of functions (or, at least one: register()). What I'd
like to do now is being able to load these plugins at program
start and reload them if I'd like to later. Problem is that the
program has to figure out by itself what *.py files are there -
and I have to make sure somehow that I get a grip on the loaded
files.

What I tried is this: I created a subdir called "pi" to hold the
files and created a file __init__.py inside it. Code follows:

from os import listdir

modlist=[]

def rel():
 for fn in listdir(__name__):
    if fn != "__init__.py": 
        if  fn[-3:] == ".py":
            mod=fn[:-3]
            if mod not in modlist:
                exec("import %s"%mod)
                modlist.append(mod)
            else:
                exec("reload (%s)"%mod)
 return(modlist)

Now I can just "import pi" and execute pi.rel() which in turn
loads all the modules that are there ('cept the ones that only
exist as pyc or pyo, but that's okay). But now I have two
problems: first, I have no idea how to call, say
pi.someplugin.dostuff(args) except constructing each and every
call as a string and exec() it - which is both error-prone and
awkward IMHO.

Second, reloading just does not seem to work right as Python is
too smart ;) for me: it knows all of them have been loaded. So I
added the reload code above but to no avail.

For testing purposes, I created a.py ... l.py containing this:

print __name__
def register():
    return ("I work for %s%s",__name__,__name__)

I get the feeling that there is something fundamentally wrong
with my approach. What would you do?

Greets,
Tobias




More information about the Python-list mailing list