Python plugins

Tobias Klausmann klausman-un080902 at
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

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

from os import listdir


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

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 ... 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?


More information about the Python-list mailing list