pluginbox.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #
  2. # Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
  3. # All rights reserved.
  4. # This component and the accompanying materials are made available
  5. # under the terms of the License "Eclipse Public License v1.0"
  6. # which accompanies this distribution, and is available
  7. # at the URL "http://www.eclipse.org/legal/epl-v10.html".
  8. #
  9. # Initial Contributors:
  10. # Nokia Corporation - initial contribution.
  11. #
  12. # Contributors:
  13. #
  14. # Description:
  15. # PluginBox module - finds classes
  16. #
  17. from os import listdir
  18. import re
  19. from types import TypeType, ModuleType
  20. import sys
  21. class PluginModule(object):
  22. """Represents a module containing plugin classes """
  23. def __init__(self, file):
  24. self.module = __import__(file)
  25. self.classes = []
  26. self.__findclasses(self.module)
  27. def __findclasses(self,module):
  28. for c in module.__dict__:
  29. mbr = module.__dict__[c]
  30. if type(mbr) == TypeType:
  31. self.classes.append(mbr)
  32. class PluginBox(object):
  33. """
  34. A container that locates all the classes in a directory.
  35. Example usage:
  36. from person import Person
  37. ps = PluginBox("plugins")
  38. people = []
  39. for i in ps.classesof(Person):
  40. people.append(i())
  41. """
  42. plugfilenamere=re.compile('^(.*)\.py$',re.I)
  43. def __init__(self, plugindirectory):
  44. self.pluginlist = []
  45. self.plugindir = plugindirectory
  46. sys.path.append(str(self.plugindir))
  47. for f in listdir(plugindirectory):
  48. m = PluginBox.plugfilenamere.match(f)
  49. if m is not None:
  50. self.pluginlist.append(PluginModule(m.groups()[0]))
  51. sys.path = sys.path[:-1]
  52. def classesof(self, classtype):
  53. """return a list of all classes that are subclasses of <classtype>"""
  54. classes = []
  55. for p in self.pluginlist:
  56. for c in p.classes:
  57. if issubclass(c, classtype):
  58. if c.__name__ != classtype.__name__:
  59. classes.append(c)
  60. return classes