configparser.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. class Error(Exception):
  2. pass
  3. class ConfigParser(object):
  4. class Section(object):
  5. def __init__(self, name):
  6. self.name = name
  7. self.options = {}
  8. def __init__(self):
  9. self.__sections = {}
  10. def read_file(self, f, source=None):
  11. self.__sections = {}
  12. section = None
  13. while True:
  14. line = f.readline()
  15. if not line:
  16. break
  17. line = line.lstrip().rstrip("\r\n")
  18. if not line or line.startswith(";"):
  19. continue
  20. sline = line.strip()
  21. if sline.startswith("[") and sline.endswith("]"):
  22. sectionName = sline[1:-1]
  23. if sectionName in self.__sections:
  24. raise Error("Multiple definitions of section '%s'" % sectionName)
  25. section = self.__sections[sectionName] = self.Section(sectionName)
  26. continue
  27. if section is None:
  28. raise Error("Option '%s' is not in a section." % line)
  29. idx = line.find("=")
  30. if idx > 0:
  31. optionName = line[:idx]
  32. optionValue = line[idx+1:]
  33. if optionName in section.options:
  34. raise Error("Multiple definitions of option '%s/%s'" % (
  35. section.name, optionName))
  36. section.options[optionName] = optionValue
  37. continue
  38. raise Error("Could not parse line: %s" % line)
  39. def has_option(self, section, option):
  40. try:
  41. self.get(section, option)
  42. except Error as e:
  43. return False
  44. return True
  45. def get(self, section, option):
  46. try:
  47. return self.__sections[section].options[option]
  48. except KeyError as e:
  49. raise Error("Option '%s/%s' not found." % (section, option))
  50. def getboolean(self, section, option):
  51. try:
  52. v = self.get(section, option).lower().strip()
  53. if v == "true":
  54. return True
  55. if v == "false":
  56. return False
  57. return bool(int(v))
  58. except ValueError as e:
  59. raise Error("Invalid boolean option '%s/%s'." % (section, option))
  60. def getint(self, section, option):
  61. try:
  62. return int(self.get(section, option))
  63. except ValueError as e:
  64. raise Error("Invalid int option '%s/%s'." % (section, option))
  65. def sections(self):
  66. return list(self.__sections.keys())
  67. def options(self, section):
  68. try:
  69. return list(self.__sections[section].options)
  70. except KeyError as e:
  71. raise Error("Section '%s' not found." % section)