blob: b0475a37d5658c14cdc6e8c4e89fc2e8f6cdefbf [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
Barry Warsawf09f6a51999-01-26 22:01:37 +000036 options(section)
37 return list of configuration options for the named section
Guido van Rossum3d209861997-12-09 16:10:31 +000038
Guido van Rossumc0780ac1999-01-30 04:35:47 +000039 read(filenames)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000040 read and parse the list of named configuration files, given by
41 name. A single filename is also allowed. Non-existing files
42 are ignored.
43
44 readfp(fp, filename=None)
45 read and parse one configuration file, given as a file object.
46 The filename defaults to fp.name; it is only used in error
47 messages.
Guido van Rossum3d209861997-12-09 16:10:31 +000048
Barry Warsawf09f6a51999-01-26 22:01:37 +000049 get(section, option, raw=0, vars=None)
50 return a string value for the named option. All % interpolations are
51 expanded in the return values, based on the defaults passed into the
52 constructor and the DEFAULT section. Additional substitutions may be
53 provided using the `vars' argument, which must be a dictionary whose
54 contents override any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +000055
Barry Warsawf09f6a51999-01-26 22:01:37 +000056 getint(section, options)
57 like get(), but convert value to an integer
Guido van Rossum3d209861997-12-09 16:10:31 +000058
Barry Warsawf09f6a51999-01-26 22:01:37 +000059 getfloat(section, options)
60 like get(), but convert value to a float
Guido van Rossum3d209861997-12-09 16:10:31 +000061
Barry Warsawf09f6a51999-01-26 22:01:37 +000062 getboolean(section, options)
63 like get(), but convert value to a boolean (currently defined as 0 or
64 1, only)
Guido van Rossum3d209861997-12-09 16:10:31 +000065"""
66
67import sys
68import string
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000069import re
Guido van Rossum3d209861997-12-09 16:10:31 +000070
71DEFAULTSECT = "DEFAULT"
72
73
74
75# exception classes
76class Error:
77 def __init__(self, msg=''):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000078 self._msg = msg
Guido van Rossum3d209861997-12-09 16:10:31 +000079 def __repr__(self):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000080 return self._msg
Guido van Rossum3d209861997-12-09 16:10:31 +000081
82class NoSectionError(Error):
83 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000084 Error.__init__(self, 'No section: %s' % section)
85 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000086
87class DuplicateSectionError(Error):
88 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000089 Error.__init__(self, "Section %s already exists" % section)
90 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000091
92class NoOptionError(Error):
93 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000094 Error.__init__(self, "No option `%s' in section: %s" %
95 (option, section))
96 self.option = option
97 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000098
99class InterpolationError(Error):
Barry Warsaw64462121998-08-06 18:48:41 +0000100 def __init__(self, reference, option, section, rawval):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000101 Error.__init__(self,
Barry Warsaw64462121998-08-06 18:48:41 +0000102 "Bad value substitution:\n"
103 "\tsection: [%s]\n"
104 "\toption : %s\n"
105 "\tkey : %s\n"
106 "\trawval : %s\n"
107 % (section, option, reference, rawval))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000108 self.reference = reference
109 self.option = option
110 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000111
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000112class MissingSectionHeaderError(Error):
113 def __init__(self, filename, lineno, line):
114 Error.__init__(
115 self,
116 'File contains no section headers.\nfile: %s, line: %d\n%s' %
117 (filename, lineno, line))
118 self.filename = filename
119 self.lineno = lineno
120 self.line = line
121
122class ParsingError(Error):
123 def __init__(self, filename):
124 Error.__init__(self, 'File contains parsing errors: %s' % filename)
125 self.filename = filename
126 self.errors = []
127
128 def append(self, lineno, line):
129 self.errors.append((lineno, line))
130 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
131
Guido van Rossum3d209861997-12-09 16:10:31 +0000132
133
134class ConfigParser:
135 def __init__(self, defaults=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000136 self.__sections = {}
137 if defaults is None:
138 self.__defaults = {}
139 else:
140 self.__defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000141
142 def defaults(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000143 return self.__defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000144
145 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000146 """Return a list of section names, excluding [DEFAULT]"""
147 # self.__sections will never have [DEFAULT] in it
148 return self.__sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000149
150 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000152
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000153 Raise DuplicateSectionError if a section by the specified name
154 already exists.
155 """
156 if self.__sections.has_key(section):
157 raise DuplicateSectionError(section)
158 self.__sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000159
160 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000162
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 The DEFAULT section is not acknowledged.
164 """
165 return self.__sections.has_key(section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000166
167 def options(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000168 try:
169 opts = self.__sections[section].copy()
170 except KeyError:
171 raise NoSectionError(section)
172 opts.update(self.__defaults)
173 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000174
175 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000176
177 """Read and parse a filename or a list of filenames.
178
179 Files that cannot be opened are silently ignored; this is
180 designed so that you can specifiy a list of potential
181 configuration file locations (e.g. current directory, user's
182 home directory, systemwide directory), and all existing
183 configuration files in the list will be read. A single
184 filename may also be given.
185 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 if type(filenames) is type(''):
187 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000188 for filename in filenames:
189 try:
190 fp = open(filename)
191 except IOError:
192 continue
193 self.__read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000194 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000195
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000196 def readfp(self, fp, filename=None):
197 """Like read() but the argument must be a file-like object.
198
199 The `fp' argument must have a `readline' method. Optional
200 second argument is the `filename', which if not given, is
201 taken from fp.name. If fp has no `name' attribute, `<???>' is
202 used.
203
204 """
205 if filename is None:
206 try:
207 filename = fp.name
208 except AttributeError:
209 filename = '<???>'
210 self.__read(fp, filename)
211
Guido van Rossume6506e71999-01-26 19:29:25 +0000212 def get(self, section, option, raw=0, vars=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 """Get an option value for a given section.
Guido van Rossum3d209861997-12-09 16:10:31 +0000214
Barry Warsawf09f6a51999-01-26 22:01:37 +0000215 All % interpolations are expanded in the return values, based on the
216 defaults passed into the constructor, unless the optional argument
217 `raw' is true. Additional substitutions may be provided using the
218 `vars' argument, which must be a dictionary whose contents overrides
219 any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +0000220
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 The section DEFAULT is special.
222 """
223 try:
224 sectdict = self.__sections[section].copy()
225 except KeyError:
226 if section == DEFAULTSECT:
227 sectdict = {}
228 else:
229 raise NoSectionError(section)
230 d = self.__defaults.copy()
231 d.update(sectdict)
Guido van Rossume6506e71999-01-26 19:29:25 +0000232 # Update with the entry specific variables
233 if vars:
234 d.update(vars)
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000235 option = self.optionxform(option)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000236 try:
237 rawval = d[option]
238 except KeyError:
239 raise NoOptionError(option, section)
240 # do the string interpolation
241 if raw:
242 return rawval
Guido van Rossum3d209861997-12-09 16:10:31 +0000243
Guido van Rossume6506e71999-01-26 19:29:25 +0000244 value = rawval # Make it a pretty variable name
Guido van Rossum72ce8581999-02-12 14:13:10 +0000245 depth = 0
246 while depth < 10: # Loop through this until it's done
247 depth = depth + 1
Guido van Rossume6506e71999-01-26 19:29:25 +0000248 if not string.find(value, "%("):
249 try:
250 value = value % d
251 except KeyError, key:
252 raise InterpolationError(key, option, section, rawval)
253 else:
254 return value
255
Guido van Rossum3d209861997-12-09 16:10:31 +0000256 def __get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000257 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000258
259 def getint(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 return self.__get(section, string.atoi, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000261
262 def getfloat(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000263 return self.__get(section, string.atof, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000264
265 def getboolean(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000266 v = self.get(section, option)
267 val = string.atoi(v)
268 if val not in (0, 1):
269 raise ValueError, 'Not a boolean: %s' % v
270 return val
Guido van Rossum3d209861997-12-09 16:10:31 +0000271
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000272 def optionxform(self, optionstr):
273 return string.lower(optionstr)
274
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000275 #
276 # Regular expressions for parsing section headers and options. Note a
277 # slight semantic change from the previous version, because of the use
278 # of \w, _ is allowed in section header names.
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000279 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000280 r'\[' # [
281 r'(?P<header>[-\w]+)' # `-', `_' or any alphanum
282 r'\]' # ]
283 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000284 OPTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000285 r'(?P<option>[-.\w]+)' # - . _ alphanum
286 r'[ \t]*[:=][ \t]*' # any number of space/tab,
287 # followed by separator
288 # (either : or =), followed
289 # by any # space/tab
290 r'(?P<value>.*)$' # everything up to eol
291 )
292
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000293 def __read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000294 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000295
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000296 The sections in setup file contains a title line at the top,
297 indicated by a name in square brackets (`[]'), plus key/value
298 options lines, indicated by `name: value' format lines.
299 Continuation are represented by an embedded newline then
300 leading whitespace. Blank lines, lines beginning with a '#',
301 and just about everything else is ignored.
302 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000303 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000304 optname = None
305 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000306 e = None # None, or an exception
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000307 while 1:
308 line = fp.readline()
309 if not line:
310 break
311 lineno = lineno + 1
312 # comment or blank line?
313 if string.strip(line) == '' or line[0] in '#;':
314 continue
315 if string.lower(string.split(line)[0]) == 'rem' \
316 and line[0] == "r": # no leading whitespace
317 continue
318 # continuation line?
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000319 if line[0] in ' \t' and cursect is not None and optname:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000320 value = string.strip(line)
321 if value:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000322 cursect[optname] = cursect[optname] + '\n ' + value
323 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000324 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000325 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000326 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000327 if mo:
328 sectname = mo.group('header')
329 if self.__sections.has_key(sectname):
330 cursect = self.__sections[sectname]
331 elif sectname == DEFAULTSECT:
332 cursect = self.__defaults
333 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000334 cursect = {'__name__': sectname}
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000335 self.__sections[sectname] = cursect
336 # So sections can't start with a continuation line
337 optname = None
338 # no section header in the file?
339 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000340 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000341 # an option line?
342 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000343 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000344 if mo:
345 optname, optval = mo.group('option', 'value')
346 optname = string.lower(optname)
347 optval = string.strip(optval)
348 # allow empty values
349 if optval == '""':
350 optval = ''
351 cursect[optname] = optval
352 else:
353 # a non-fatal parsing error occurred. set up the
354 # exception but keep going. the exception will be
355 # raised at the end of the file and will contain a
356 # list of all bogus lines
357 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000358 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000359 e.append(lineno, `line`)
360 # if any parsing errors occurred, raise an exception
361 if e:
362 raise e