zconfig.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import ConfigParser
  2. import zinterval
  3. import StringIO
  4. import os
  5. import zunit
  6. class ZConfigParser:
  7. def __init__(self, configfile, defaultoptions={}):
  8. self.config = ConfigParser.ConfigParser(defaults=defaultoptions)
  9. self.readZConfig(configfile)
  10. def readZConfig(self, filename):
  11. filename = os.path.abspath(filename)
  12. data = "[DEFAULT]\r\n"
  13. try:
  14. fp = open(filename)
  15. except IOError, e:
  16. if e.errno == 2 or e.errno == 13:
  17. raise IOError(e.errno, 'Unable to open config file \''+filename+'\'. ' + e.strerror)
  18. else:
  19. raise
  20. for line in fp:
  21. data += line
  22. fp.close()
  23. self.config.readfp(StringIO.StringIO(data))
  24. def options(self):
  25. return self.config.defaults()
  26. def get(self, option):
  27. return self.config.get('DEFAULT', option)
  28. def getint(self, option):
  29. return self.config.getint('DEFAULT', option)
  30. def getboolean(self, option):
  31. return self.config.getboolean('DEFAULT', option)
  32. # get interval field in seconds
  33. def getinterval(self, option):
  34. value = self.config.get('DEFAULT', option)
  35. return zinterval.parse(value)
  36. def getunitbyte(self, option):
  37. value = self.config.get('DEFAULT', option)
  38. return zunit.parseUnitByte(value)
  39. ## Get a dict of a list of options
  40. # if you have the following options in the config file:
  41. # test_option1, test_option2, test_option3
  42. # getdict('test', ['option1', 'option2', 'option3'])
  43. #
  44. def getdict(self, prefix, options):
  45. data = {}
  46. for option in options:
  47. data[option] = self.get(prefix+'_'+option)
  48. return data