Wednesday, April 24, 2013

A Simple Python Plugin Framework

This framework is somewhat different than those currently out there, most of those either:
  • don't allow dynamic plugins
  • require you to use nasty hooks
  • require specifically formatted imports
  • require plugins to all be in one place
This script however allows plugins to:
  • be dynamically loaded
  • be a subclass of a master plugin class
  • have any name
  • be in many different folders
The general idea is that you give the function a path, and the base-class that all plugins are subclasses of, then it iterates through the path, finding python files, loading them, and then searching them for any classes that are subclasses of the class you want. When it gets done, it returns them:

Code

import inspect
import os
import sys
def load_plugins(plugin_path, instance):
'''Loads a set of plugins at the given path.

Arguments:
plugin_path - the OS path to look for plugins at.
instance - classes of this instance will be returned
'''
plugins = []
plugin_dir = os.path.realpath(plugin_path)
sys.path.append(plugin_dir)

for f in os.listdir(plugin_dir):
if f.endswith(".py"):
name = f[:-3]
elif f.endswith(".pyc"):
name = f[:-4]
elif os.path.isdir(os.path.join(plugin_dir, f)):
name = f
else:
continue

try:
mod = __import__(name, globals(), locals(), [], 0)

for piece in inspect.getmembers(mod):
if isinstance(piece, instance):
plugins.append(piece)

except ImportError as e:
print(e)
pass # problem importing

return plugins

No comments:

Post a Comment