1 """Configuration file parser.
3 A setup file consists of sections, lead by a "[section]" header,
4 and followed by "name: value" entries, with continuations and such in
7 The option values can contain format strings which refer to other values in
8 the same section, or values in a special [DEFAULT] section.
12 something: %(dir)s/whatever
14 would resolve the "%(dir)s" to the value of dir. All reference
15 expansions are done late, on demand.
17 Intrinsic defaults can be specified by passing them into the
18 ConfigParser constructor as a dictionary.
22 ConfigParser -- responsible for for parsing a list of
23 configuration files, and managing the parsed database.
27 __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.
34 return all the configuration section names, sans DEFAULT
37 return whether the given section exists
39 has_option(section, option)
40 return whether the given option exists in the given section
43 return list of configuration options for the named section
46 read and parse the list of named configuration files, given by
47 name. A single filename is also allowed. Non-existing files
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
53 messages (if fp has no `name' attribute, the string `<???>' is used).
55 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.
62 getint(section, options)
63 like get(), but convert value to an integer
65 getfloat(section, options)
66 like get(), but convert value to a float
68 getboolean(section, options)
69 like get(), but convert value to a boolean (currently case
70 insensitively defined as 0, false, no, off for 0, and 1, true,
71 yes, on for 1). Returns 0 or 1.
73 remove_section(section)
74 remove the given file section and all its options
76 remove_option(section, option)
77 remove the given option from the given section
79 set(section, option, value)
83 write the configuration state in .ini format
89 __all__ = [
"NoSectionError",
"DuplicateSectionError",
"NoOptionError",
90 "InterpolationError",
"InterpolationDepthError",
"ParsingError",
91 "MissingSectionHeaderError",
"ConfigParser",
92 "MAX_INTERPOLATION_DEPTH"]
94 DEFAULTSECT =
"DEFAULT"
96 MAX_INTERPOLATION_DEPTH = 10
104 Exception.__init__(self, msg)
111 Error.__init__(self,
'No section: %s' % section)
116 Error.__init__(self,
"Section %s already exists" % section)
121 Error.__init__(self,
"No option `%s' in section: %s" %
127 def __init__(self, reference, option, section, rawval):
129 "Bad value substitution:\n"
134 % (section, option, reference, rawval))
142 "Value interpolation too deeply recursive:\n"
146 % (section, option, rawval))
152 Error.__init__(self,
'File contains parsing errors: %s' % filename)
157 self.errors.append((lineno, line))
158 self.
_msg = self.
_msg +
'\n\t[line %2d]: %s' % (lineno, line)
164 'File contains no section headers.\nfile: %s, line: %d\n%s' %
165 (filename, lineno, line))
184 """Return a list of section names, excluding [DEFAULT]"""
186 return self.__sections.keys()
189 """Create a new section in the configuration.
191 Raise DuplicateSectionError if a section by the specified name
194 if self.__sections.has_key(section):
199 """Indicate whether the named section is present in the configuration.
201 The DEFAULT section is not acknowledged.
206 """Return a list of option names for the given section name."""
212 if opts.has_key(
'__name__'):
217 """Read and parse a filename or a list of filenames.
219 Files that cannot be opened are silently ignored; this is
220 designed so that you can specify a list of potential
221 configuration file locations (e.g. current directory, user's
222 home directory, systemwide directory), and all existing
223 configuration files in the list will be read. A single
224 filename may also be given.
226 if type(filenames)
in types.StringTypes:
227 filenames = [filenames]
228 for filename
in filenames:
237 """Like read() but the argument must be a file-like object.
239 The `fp' argument must have a `readline' method. Optional
240 second argument is the `filename', which if not given, is
241 taken from fp.name. If fp has no `name' attribute, `<???>' is
248 except AttributeError:
252 def get(self, section, option, raw=0, vars=None):
253 """Get an option value for a given section.
255 All % interpolations are expanded in the return values, based on the
256 defaults passed into the constructor, unless the optional argument
257 `raw' is true. Additional substitutions may be provided using the
258 `vars' argument, which must be a dictionary whose contents overrides
259 any pre-existing defaults.
261 The section DEFAULT is special.
266 if section == DEFAULTSECT:
270 d = self.__defaults.copy()
289 if value.find(
"%(") >= 0:
292 except KeyError, key:
296 if value.find(
"%(") >= 0:
300 def __get(self, section, conv, option):
301 return conv(self.
get(section, option))
304 return self.
__get(section, string.atoi, option)
307 return self.
__get(section, string.atof, option)
310 states = {
'1': 1,
'yes': 1,
'true': 1,
'on': 1,
311 '0': 0,
'no': 0,
'false': 0,
'off': 0}
312 v = self.
get(section, option)
313 if not states.has_key(v.lower()):
314 raise ValueError,
'Not a boolean: %s' % v
315 return states[v.lower()]
318 return optionstr.lower()
321 """Check for the existence of a given option in a given section."""
322 if not section
or section ==
"DEFAULT":
323 return self.__defaults.has_key(option)
330 def set(self, section, option, value):
332 if not section
or section ==
"DEFAULT":
340 sectdict[option] = value
343 """Write an .ini-format representation of the configuration state."""
345 fp.write(
"[DEFAULT]\n")
346 for (key, value)
in self.__defaults.items():
347 fp.write(
"%s = %s\n" % (key,
str(value).
replace(
'\n',
'\n\t')))
350 fp.write(
"[" + section +
"]\n")
352 for (key, value)
in sectdict.items():
353 if key ==
"__name__":
355 fp.write(
"%s = %s\n" % (key,
str(value).
replace(
'\n',
'\n\t')))
359 """Remove an option."""
360 if not section
or section ==
"DEFAULT":
368 existed = sectdict.has_key(option)
374 """Remove a file section."""
375 if self.__sections.has_key(section):
385 SECTCRE = re.compile(
391 r'(?P<option>[]\-[\w_.*,(){}]+)'
392 r'[ \t]*(?P<vi>[:=])[ \t]*'
399 def __read(self, fp, fpname):
400 """Parse a sectioned setup file.
402 The sections in setup file contains a title line at the top,
403 indicated by a name in square brackets (`[]'), plus key/value
404 options lines, indicated by `name: value' format lines.
405 Continuation are represented by an embedded newline then
406 leading whitespace. Blank lines, lines beginning with a '#',
407 and just about everything else is ignored.
419 if line.strip() ==
'' or line[0]
in '#;':
421 if line.split()[0].
lower() ==
'rem' \
425 if line[0]
in ' \t' and cursect
is not None and optname:
429 cursect[k] =
"%s\n%s" % (cursect[k], value)
433 mo = self.SECTCRE.match(line)
435 sectname = mo.group(
'header')
436 if self.__sections.has_key(sectname):
438 elif sectname == DEFAULTSECT:
441 cursect = {
'__name__': sectname}
446 elif cursect
is None:
450 mo = self.OPTCRE.match(line)
452 optname, vi, optval = mo.group(
'option',
'vi',
'value')
453 if vi
in (
'=',
':')
and ';' in optval:
456 pos = optval.find(
';')
457 if pos
and optval[pos-1]
in string.whitespace:
458 optval = optval[:pos]
459 optval = optval.strip()
471 e.append(lineno, `line`)