blob: f0611f687996abd7d9abc37d291e1d68a9503e1f [file] [log] [blame]
Guido van Rossum3d209861997-12-09 16:10:31 +00001"""Configuration file parser.
2
3A setup file consists of sections, lead by a "[section]" header,
4and followed by "name: value" entries, with continuations and such in
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00005the style of RFC 822.
Guido van Rossum3d209861997-12-09 16:10:31 +00006
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00007The option values can contain format strings which refer to other values in
8the same section, or values in a special [DEFAULT] section.
9
Guido van Rossum3d209861997-12-09 16:10:31 +000010For example:
11
12 something: %(dir)s/whatever
13
14would resolve the "%(dir)s" to the value of dir. All reference
15expansions are done late, on demand.
16
17Intrinsic defaults can be specified by passing them into the
18ConfigParser constructor as a dictionary.
19
20class:
21
22ConfigParser -- responsible for for parsing a list of
23 configuration files, and managing the parsed database.
24
25 methods:
26
Barry Warsawf09f6a51999-01-26 22:01:37 +000027 __init__(defaults=None)
28 create the parser and specify a dictionary of intrinsic defaults. The
29 keys must be strings, the values must be appropriate for %()s string
30 interpolation. Note that `__name__' is always an intrinsic default;
31 it's value is the section's name.
Guido van Rossum3d209861997-12-09 16:10:31 +000032
Barry Warsawf09f6a51999-01-26 22:01:37 +000033 sections()
34 return all the configuration section names, sans DEFAULT
Guido van Rossum3d209861997-12-09 16:10:31 +000035
Guido van Rossuma5a24b71999-10-04 19:58:22 +000036 has_section(section)
37 return whether the given section exists
38
Barry Warsawf09f6a51999-01-26 22:01:37 +000039 options(section)
40 return list of configuration options for the named section
Guido van Rossum3d209861997-12-09 16:10:31 +000041
Guido van Rossuma5a24b71999-10-04 19:58:22 +000042 has_option(section, option)
43 return whether the given section has the given option
44
Guido van Rossumc0780ac1999-01-30 04:35:47 +000045 read(filenames)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000046 read and parse the list of named configuration files, given by
47 name. A single filename is also allowed. Non-existing files
48 are ignored.
49
50 readfp(fp, filename=None)
51 read and parse one configuration file, given as a file object.
52 The filename defaults to fp.name; it is only used in error
Barry Warsaw25394511999-10-12 16:12:48 +000053 messages (if fp has no `name' attribute, the string `<???>' is used).
Guido van Rossum3d209861997-12-09 16:10:31 +000054
Barry Warsawf09f6a51999-01-26 22:01:37 +000055 get(section, option, raw=0, vars=None)
56 return a string value for the named option. All % interpolations are
57 expanded in the return values, based on the defaults passed into the
58 constructor and the DEFAULT section. Additional substitutions may be
59 provided using the `vars' argument, which must be a dictionary whose
60 contents override any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +000061
Barry Warsawf09f6a51999-01-26 22:01:37 +000062 getint(section, options)
63 like get(), but convert value to an integer
Guido van Rossum3d209861997-12-09 16:10:31 +000064
Barry Warsawf09f6a51999-01-26 22:01:37 +000065 getfloat(section, options)
66 like get(), but convert value to a float
Guido van Rossum3d209861997-12-09 16:10:31 +000067
Barry Warsawf09f6a51999-01-26 22:01:37 +000068 getboolean(section, options)
69 like get(), but convert value to a boolean (currently defined as 0 or
70 1, only)
Guido van Rossum3d209861997-12-09 16:10:31 +000071"""
72
73import sys
74import string
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000075import re
Guido van Rossum3d209861997-12-09 16:10:31 +000076
77DEFAULTSECT = "DEFAULT"
78
79
80
81# exception classes
82class Error:
83 def __init__(self, msg=''):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000084 self._msg = msg
Guido van Rossum3d209861997-12-09 16:10:31 +000085 def __repr__(self):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000086 return self._msg
Guido van Rossum3d209861997-12-09 16:10:31 +000087
88class NoSectionError(Error):
89 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000090 Error.__init__(self, 'No section: %s' % section)
91 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000092
93class DuplicateSectionError(Error):
94 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000095 Error.__init__(self, "Section %s already exists" % section)
96 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000097
98class NoOptionError(Error):
99 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 Error.__init__(self, "No option `%s' in section: %s" %
101 (option, section))
102 self.option = option
103 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000104
105class InterpolationError(Error):
Barry Warsaw64462121998-08-06 18:48:41 +0000106 def __init__(self, reference, option, section, rawval):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 Error.__init__(self,
Barry Warsaw64462121998-08-06 18:48:41 +0000108 "Bad value substitution:\n"
109 "\tsection: [%s]\n"
110 "\toption : %s\n"
111 "\tkey : %s\n"
112 "\trawval : %s\n"
113 % (section, option, reference, rawval))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000114 self.reference = reference
115 self.option = option
116 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000117
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000118class MissingSectionHeaderError(Error):
119 def __init__(self, filename, lineno, line):
120 Error.__init__(
121 self,
122 'File contains no section headers.\nfile: %s, line: %d\n%s' %
123 (filename, lineno, line))
124 self.filename = filename
125 self.lineno = lineno
126 self.line = line
127
128class ParsingError(Error):
129 def __init__(self, filename):
130 Error.__init__(self, 'File contains parsing errors: %s' % filename)
131 self.filename = filename
132 self.errors = []
133
134 def append(self, lineno, line):
135 self.errors.append((lineno, line))
136 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
137
Guido van Rossum3d209861997-12-09 16:10:31 +0000138
139
140class ConfigParser:
141 def __init__(self, defaults=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000142 self.__sections = {}
143 if defaults is None:
144 self.__defaults = {}
145 else:
146 self.__defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000147
148 def defaults(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000149 return self.__defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000150
151 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000152 """Return a list of section names, excluding [DEFAULT]"""
153 # self.__sections will never have [DEFAULT] in it
154 return self.__sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000155
156 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000157 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000158
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000159 Raise DuplicateSectionError if a section by the specified name
160 already exists.
161 """
162 if self.__sections.has_key(section):
163 raise DuplicateSectionError(section)
164 self.__sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000165
166 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000168
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000169 The DEFAULT section is not acknowledged.
170 """
171 return self.__sections.has_key(section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000172
173 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000174 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000175 try:
176 opts = self.__sections[section].copy()
177 except KeyError:
178 raise NoSectionError(section)
179 opts.update(self.__defaults)
180 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000181
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000182 def has_option(self, section, option):
183 """Return whether the given section has the given option."""
184 try:
185 opts = self.__sections[section]
186 except KeyError:
187 raise NoSectionError(section)
188 return opts.has_key(option)
189
Guido van Rossum3d209861997-12-09 16:10:31 +0000190 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000191 """Read and parse a filename or a list of filenames.
192
193 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000194 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000195 configuration file locations (e.g. current directory, user's
196 home directory, systemwide directory), and all existing
197 configuration files in the list will be read. A single
198 filename may also be given.
199 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 if type(filenames) is type(''):
201 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000202 for filename in filenames:
203 try:
204 fp = open(filename)
205 except IOError:
206 continue
207 self.__read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000208 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000209
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000210 def readfp(self, fp, filename=None):
211 """Like read() but the argument must be a file-like object.
212
213 The `fp' argument must have a `readline' method. Optional
214 second argument is the `filename', which if not given, is
215 taken from fp.name. If fp has no `name' attribute, `<???>' is
216 used.
217
218 """
219 if filename is None:
220 try:
221 filename = fp.name
222 except AttributeError:
223 filename = '<???>'
224 self.__read(fp, filename)
225
Guido van Rossume6506e71999-01-26 19:29:25 +0000226 def get(self, section, option, raw=0, vars=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000227 """Get an option value for a given section.
Guido van Rossum3d209861997-12-09 16:10:31 +0000228
Barry Warsawf09f6a51999-01-26 22:01:37 +0000229 All % interpolations are expanded in the return values, based on the
230 defaults passed into the constructor, unless the optional argument
231 `raw' is true. Additional substitutions may be provided using the
232 `vars' argument, which must be a dictionary whose contents overrides
233 any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +0000234
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 The section DEFAULT is special.
236 """
237 try:
238 sectdict = self.__sections[section].copy()
239 except KeyError:
240 if section == DEFAULTSECT:
241 sectdict = {}
242 else:
243 raise NoSectionError(section)
244 d = self.__defaults.copy()
245 d.update(sectdict)
Guido van Rossume6506e71999-01-26 19:29:25 +0000246 # Update with the entry specific variables
247 if vars:
248 d.update(vars)
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000249 option = self.optionxform(option)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000250 try:
251 rawval = d[option]
252 except KeyError:
253 raise NoOptionError(option, section)
254 # do the string interpolation
255 if raw:
256 return rawval
Guido van Rossum3d209861997-12-09 16:10:31 +0000257
Guido van Rossume6506e71999-01-26 19:29:25 +0000258 value = rawval # Make it a pretty variable name
Guido van Rossum72ce8581999-02-12 14:13:10 +0000259 depth = 0
260 while depth < 10: # Loop through this until it's done
261 depth = depth + 1
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000262 if string.find(value, "%(") >= 0:
Guido van Rossume6506e71999-01-26 19:29:25 +0000263 try:
264 value = value % d
265 except KeyError, key:
266 raise InterpolationError(key, option, section, rawval)
267 else:
268 return value
269
Guido van Rossum3d209861997-12-09 16:10:31 +0000270 def __get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000271 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000272
273 def getint(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000274 return self.__get(section, string.atoi, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000275
276 def getfloat(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000277 return self.__get(section, string.atof, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000278
279 def getboolean(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000280 v = self.get(section, option)
281 val = string.atoi(v)
282 if val not in (0, 1):
283 raise ValueError, 'Not a boolean: %s' % v
284 return val
Guido van Rossum3d209861997-12-09 16:10:31 +0000285
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000286 def optionxform(self, optionstr):
287 return string.lower(optionstr)
288
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000289 #
290 # Regular expressions for parsing section headers and options. Note a
291 # slight semantic change from the previous version, because of the use
292 # of \w, _ is allowed in section header names.
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000293 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000294 r'\[' # [
295 r'(?P<header>[-\w]+)' # `-', `_' or any alphanum
296 r'\]' # ]
297 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000298 OPTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000299 r'(?P<option>[-.\w]+)' # - . _ alphanum
300 r'[ \t]*[:=][ \t]*' # any number of space/tab,
301 # followed by separator
302 # (either : or =), followed
303 # by any # space/tab
304 r'(?P<value>.*)$' # everything up to eol
305 )
306
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000307 def __read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000308 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000309
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000310 The sections in setup file contains a title line at the top,
311 indicated by a name in square brackets (`[]'), plus key/value
312 options lines, indicated by `name: value' format lines.
313 Continuation are represented by an embedded newline then
314 leading whitespace. Blank lines, lines beginning with a '#',
315 and just about everything else is ignored.
316 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000317 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000318 optname = None
319 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000320 e = None # None, or an exception
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000321 while 1:
322 line = fp.readline()
323 if not line:
324 break
325 lineno = lineno + 1
326 # comment or blank line?
327 if string.strip(line) == '' or line[0] in '#;':
328 continue
329 if string.lower(string.split(line)[0]) == 'rem' \
330 and line[0] == "r": # no leading whitespace
331 continue
332 # continuation line?
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000333 if line[0] in ' \t' and cursect is not None and optname:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000334 value = string.strip(line)
335 if value:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000336 cursect[optname] = cursect[optname] + '\n ' + value
337 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000338 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000339 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000340 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000341 if mo:
342 sectname = mo.group('header')
343 if self.__sections.has_key(sectname):
344 cursect = self.__sections[sectname]
345 elif sectname == DEFAULTSECT:
346 cursect = self.__defaults
347 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000348 cursect = {'__name__': sectname}
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000349 self.__sections[sectname] = cursect
350 # So sections can't start with a continuation line
351 optname = None
352 # no section header in the file?
353 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000354 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000355 # an option line?
356 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000357 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000358 if mo:
359 optname, optval = mo.group('option', 'value')
360 optname = string.lower(optname)
361 optval = string.strip(optval)
362 # allow empty values
363 if optval == '""':
364 optval = ''
365 cursect[optname] = optval
366 else:
367 # a non-fatal parsing error occurred. set up the
368 # exception but keep going. the exception will be
369 # raised at the end of the file and will contain a
370 # list of all bogus lines
371 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000372 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000373 e.append(lineno, `line`)
374 # if any parsing errors occurred, raise an exception
375 if e:
376 raise e