Accueil / Blog / Métier / Archives / A very Simple and Stupid plugin system in python

A very Simple and Stupid plugin system in python

Par Mathieu Leplatre publié 02/09/2011, édité le 11/03/2015

Two convenience functions for listing and importing python modules :

# utils.py

import os

def plugins_list(plugins_dirs):
    """ List all python modules in specified plugins folders """
    for path in plugins_dirs.split(os.pathsep):
        for filename in os.listdir(path):
            name, ext = os.path.splitext(filename)
            if ext.endswith(".py"):
                yield name


def import_plugins(plugins_dirs, env):
    """ Import modules into specified environment (symbol table) """
    for p in plugins_list(plugins_dirs):
        m = __import__(p, env)
        env[p] = m

And now use import_plugins() wherever you need to use them !

# yourapp.py

import os
from utils import import_plugins

plugins_dirs = "plugins/:module/plugins/"
sys.path.extend(plugins_dirs.split(os.pathsep))

import_plugins(plugins_dirs, globals())

Note that in order to list all sub-classes of a specific one, you can use this recursive function.

That's all folks !

It is very simple and very stupid, but useful :) You might now want to have a look at serious stuff like Yapsy or PkgResouces.

ABONNEZ-VOUS À LA NEWSLETTER !