Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 1 | """Configuration file parser. |
| 2 | |
| 3 | A setup file consists of sections, lead by a "[section]" header, |
| 4 | and followed by "name: value" entries, with continuations and such in |
| 5 | the style of rfc822. |
| 6 | |
| 7 | The option values can contain format strings which refer to other |
| 8 | values in the same section, or values in a special [DEFAULT] section. |
| 9 | For example: |
| 10 | |
| 11 | something: %(dir)s/whatever |
| 12 | |
| 13 | would resolve the "%(dir)s" to the value of dir. All reference |
| 14 | expansions are done late, on demand. |
| 15 | |
| 16 | Intrinsic defaults can be specified by passing them into the |
| 17 | ConfigParser constructor as a dictionary. |
| 18 | |
| 19 | class: |
| 20 | |
| 21 | ConfigParser -- responsible for for parsing a list of |
| 22 | configuration files, and managing the parsed database. |
| 23 | |
| 24 | methods: |
| 25 | |
| 26 | __init__(defaults=None) -- create the parser and specify a |
| 27 | dictionary of intrinsic defaults. The |
| 28 | keys must be strings, the values must |
| 29 | be appropriate for %()s string |
| 30 | interpolation. Note that `name' is |
| 31 | always an intrinsic default; it's value |
| 32 | is the section's name. |
| 33 | |
| 34 | sections() -- return all the configuration section names, sans DEFAULT |
| 35 | |
| 36 | options(section) -- return list of configuration options for the named |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 37 | section |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 38 | |
| 39 | read(*filenames) -- read and parse the list of named configuration files |
| 40 | |
| 41 | get(section, option, raw=0) -- return a string value for the named |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 42 | option. All % interpolations are |
| 43 | expanded in the return values, based on |
| 44 | the defaults passed into the constructor |
| 45 | and the DEFAULT section. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 46 | |
| 47 | getint(section, options) -- like get(), but convert value to an integer |
| 48 | |
| 49 | getfloat(section, options) -- like get(), but convert value to a float |
| 50 | |
| 51 | getboolean(section, options) -- like get(), but convert value to |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 52 | a boolean (currently defined as 0 |
| 53 | or 1, only) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 54 | """ |
| 55 | |
| 56 | import sys |
| 57 | import string |
| 58 | import regex |
| 59 | from types import ListType |
| 60 | |
| 61 | |
| 62 | SECTHEAD_RE = "^\[\([-A-Za-z0-9]*\)\][" + string.whitespace + "]*$" |
| 63 | secthead_cre = regex.compile(SECTHEAD_RE) |
| 64 | OPTION_RE = "^\([-A-Za-z0-9.]+\)\(:\|[" + string.whitespace + "]*=\)\(.*\)$" |
| 65 | option_cre = regex.compile(OPTION_RE) |
| 66 | |
| 67 | DEFAULTSECT = "DEFAULT" |
| 68 | |
| 69 | |
| 70 | |
| 71 | # exception classes |
| 72 | class Error: |
| 73 | def __init__(self, msg=''): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 74 | self.__msg = msg |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 75 | def __repr__(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 76 | return self.__msg |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 77 | |
| 78 | class NoSectionError(Error): |
| 79 | def __init__(self, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 80 | Error.__init__(self, 'No section: %s' % section) |
| 81 | self.section = section |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 82 | |
| 83 | class DuplicateSectionError(Error): |
| 84 | def __init__(self, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 85 | Error.__init__(self, "Section %s already exists" % section) |
| 86 | self.section = section |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 87 | |
| 88 | class NoOptionError(Error): |
| 89 | def __init__(self, option, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 90 | Error.__init__(self, "No option `%s' in section: %s" % |
| 91 | (option, section)) |
| 92 | self.option = option |
| 93 | self.section = section |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 94 | |
| 95 | class InterpolationError(Error): |
| 96 | def __init__(self, reference, option, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 97 | Error.__init__(self, |
| 98 | "Bad value substitution: sect `%s', opt `%s', ref `%s'" |
| 99 | % (section, option, reference)) |
| 100 | self.reference = reference |
| 101 | self.option = option |
| 102 | self.section = section |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 103 | |
| 104 | |
| 105 | |
| 106 | class ConfigParser: |
| 107 | def __init__(self, defaults=None): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 108 | self.__sections = {} |
| 109 | if defaults is None: |
| 110 | self.__defaults = {} |
| 111 | else: |
| 112 | self.__defaults = defaults |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 113 | |
| 114 | def defaults(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 115 | return self.__defaults |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 116 | |
| 117 | def sections(self): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 118 | """Return a list of section names, excluding [DEFAULT]""" |
| 119 | # self.__sections will never have [DEFAULT] in it |
| 120 | return self.__sections.keys() |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 121 | |
| 122 | def add_section(self, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 123 | """Create a new section in the configuration. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 124 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 125 | Raise DuplicateSectionError if a section by the specified name |
| 126 | already exists. |
| 127 | """ |
| 128 | if self.__sections.has_key(section): |
| 129 | raise DuplicateSectionError(section) |
| 130 | self.__sections[section] = {} |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 131 | |
| 132 | def has_section(self, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 133 | """Indicate whether the named section is present in the configuration. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 134 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 135 | The DEFAULT section is not acknowledged. |
| 136 | """ |
| 137 | return self.__sections.has_key(section) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 138 | |
| 139 | def options(self, section): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 140 | try: |
| 141 | opts = self.__sections[section].copy() |
| 142 | except KeyError: |
| 143 | raise NoSectionError(section) |
| 144 | opts.update(self.__defaults) |
| 145 | return opts.keys() |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 146 | |
| 147 | def read(self, filenames): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 148 | """Read and parse a list of filenames.""" |
| 149 | if type(filenames) is type(''): |
| 150 | filenames = [filenames] |
| 151 | for file in filenames: |
| 152 | try: |
| 153 | fp = open(file, 'r') |
| 154 | self.__read(fp) |
| 155 | except IOError: |
| 156 | pass |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 157 | |
| 158 | def get(self, section, option, raw=0): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 159 | """Get an option value for a given section. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 160 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 161 | All % interpolations are expanded in the return values, based |
| 162 | on the defaults passed into the constructor. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 163 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 164 | The section DEFAULT is special. |
| 165 | """ |
| 166 | try: |
| 167 | sectdict = self.__sections[section].copy() |
| 168 | except KeyError: |
| 169 | if section == DEFAULTSECT: |
| 170 | sectdict = {} |
| 171 | else: |
| 172 | raise NoSectionError(section) |
| 173 | d = self.__defaults.copy() |
| 174 | d.update(sectdict) |
| 175 | option = string.lower(option) |
| 176 | try: |
| 177 | rawval = d[option] |
| 178 | except KeyError: |
| 179 | raise NoOptionError(option, section) |
| 180 | # do the string interpolation |
| 181 | if raw: |
| 182 | return rawval |
| 183 | try: |
| 184 | return rawval % d |
| 185 | except KeyError, key: |
| 186 | raise InterpolationError(key, option, section) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 187 | |
| 188 | def __get(self, section, conv, option): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 189 | return conv(self.get(section, option)) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 190 | |
| 191 | def getint(self, section, option): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 192 | return self.__get(section, string.atoi, option) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 193 | |
| 194 | def getfloat(self, section, option): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 195 | return self.__get(section, string.atof, option) |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 196 | |
| 197 | def getboolean(self, section, option): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 198 | v = self.get(section, option) |
| 199 | val = string.atoi(v) |
| 200 | if val not in (0, 1): |
| 201 | raise ValueError, 'Not a boolean: %s' % v |
| 202 | return val |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 203 | |
| 204 | def __read(self, fp): |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 205 | """Parse a sectioned setup file. |
Guido van Rossum | 3d20986 | 1997-12-09 16:10:31 +0000 | [diff] [blame] | 206 | |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 207 | The sections in setup file contains a title line at the top, |
| 208 | indicated by a name in square brackets (`[]'), plus key/value |
| 209 | options lines, indicated by `name: value' format lines. |
| 210 | Continuation are represented by an embedded newline then |
| 211 | leading whitespace. Blank lines, lines beginning with a '#', |
| 212 | and just about everything else is ignored. |
| 213 | """ |
| 214 | cursect = None # None, or a dictionary |
| 215 | optname = None |
| 216 | lineno = 0 |
| 217 | while 1: |
| 218 | line = fp.readline() |
| 219 | if not line: |
| 220 | break |
| 221 | lineno = lineno + 1 |
| 222 | # comment or blank line? |
| 223 | if string.strip(line) == '' or line[0] in '#;': |
| 224 | continue |
| 225 | if string.lower(string.split(line)[0]) == 'rem' \ |
| 226 | and line[0] == "r": # no leading whitespace |
| 227 | continue |
| 228 | # continuation line? |
| 229 | if line[0] in ' \t' and cursect <> None and optname: |
| 230 | value = string.strip(line) |
| 231 | if value: |
| 232 | cursect = cursect[optname] + '\n ' + value |
| 233 | # a section header? |
| 234 | elif secthead_cre.match(line) >= 0: |
| 235 | sectname = secthead_cre.group(1) |
| 236 | if self.__sections.has_key(sectname): |
| 237 | cursect = self.__sections[sectname] |
| 238 | elif sectname == DEFAULTSECT: |
| 239 | cursect = self.__defaults |
| 240 | else: |
| 241 | cursect = {'name': sectname} |
| 242 | self.__sections[sectname] = cursect |
| 243 | # So sections can't start with a continuation line. |
| 244 | optname = None |
| 245 | # an option line? |
| 246 | elif option_cre.match(line) >= 0: |
| 247 | optname, optval = option_cre.group(1, 3) |
| 248 | optname = string.lower(optname) |
| 249 | optval = string.strip(optval) |
| 250 | # allow empty values |
| 251 | if optval == '""': |
| 252 | optval = '' |
| 253 | cursect[optname] = optval |
| 254 | # an error |
| 255 | else: |
| 256 | print 'Error in %s at %d: %s', (fp.name, lineno, `line`) |