cryptonas/bin/Plugins.py

67 lines
1.6 KiB
Python

# $Id$
import imp
import os
import logging
class PluginManager:
"""manage available plugins"""
def __init__(self, cbox, plugin_dirs="."):
self.cbox = cbox
self.log = logging.getLogger("CryptoBox")
if hasattr(plugin_dirs, "__iter__"):
self.plugin_dirs = [os.path.abspath(dir) for dir in plugin_dirs]
else:
self.plugin_dirs = [os.path.abspath(plugin_dirs)]
self.pluginList = self.__getAllPlugins()
def getPlugins(self):
return self.pluginList[:]
def getPlugin(self, name):
for p in self.pluginList[:]:
if p.getName() == name:
return p
return None
def __getAllPlugins(self):
list = []
for plfile in self.__getPluginFiles():
list.append(self.__getPluginClass(os.path.basename(plfile)[:-3]))
return list
def __getPluginClass(self, name):
for plfile in self.__getPluginFiles():
if name == os.path.basename(plfile)[:-3]:
try:
pl_class = getattr(imp.load_source(name, plfile), name)
except AttributeError:
return None
return pl_class(self.cbox, os.path.dirname(plfile))
else:
return None
def __getPluginFiles(self):
result = []
for dir in [os.path.abspath(e) for e in self.plugin_dirs if os.access(e, os.R_OK) and os.path.isdir(e)]:
for plname in [f for f in os.listdir(dir)]:
pldir = os.path.join(dir, plname)
plfile = os.path.join(pldir, plname + ".py")
if os.path.isfile(plfile) and os.access(plfile, os.R_OK):
result.append(plfile)
return result
if __name__ == "__main__":
x = PluginManager(None, "../plugins")
for a in x.getPlugins():
if not a is None:
print "Plugin: %s" % a.getName()