blob: 7c2eba5cffc38d10f6054ef5b67315d2fd29cd56 [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
Eric S. Raymond649685a2000-07-14 14:28:22 +000039 has_option(section, option)
40 return whether the given option exists in the given section
41
Barry Warsawf09f6a51999-01-26 22:01:37 +000042 options(section)
43 return list of configuration options for the named section
Guido van Rossum3d209861997-12-09 16:10:31 +000044
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
Neal Norwitzf680cc42002-12-17 01:56:47 +000055 get(section, option, raw=False, vars=None)
Barry Warsawf09f6a51999-01-26 22:01:37 +000056 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)
Guido van Rossumfb06f752001-10-04 19:58:46 +000069 like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +000070 insensitively defined as 0, false, no, off for False, and 1, true,
71 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +000072
Neal Norwitzf680cc42002-12-17 01:56:47 +000073 items(section, raw=False, vars=None)
Fred Drake2ca041f2002-09-27 15:49:56 +000074 return a list of tuples with (name, value) for each option
75 in the section.
76
Eric S. Raymond649685a2000-07-14 14:28:22 +000077 remove_section(section)
Tim Peters88869f92001-01-14 23:36:06 +000078 remove the given file section and all its options
Eric S. Raymond649685a2000-07-14 14:28:22 +000079
80 remove_option(section, option)
Tim Peters88869f92001-01-14 23:36:06 +000081 remove the given option from the given section
Eric S. Raymond649685a2000-07-14 14:28:22 +000082
83 set(section, option, value)
84 set the given option
85
86 write(fp)
Tim Peters88869f92001-01-14 23:36:06 +000087 write the configuration state in .ini format
Guido van Rossum3d209861997-12-09 16:10:31 +000088"""
89
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000090import re
Guido van Rossum3d209861997-12-09 16:10:31 +000091
Fred Drake8d5dd982002-12-30 23:51:45 +000092__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
93 "InterpolationError", "InterpolationDepthError",
94 "InterpolationSyntaxError", "ParsingError",
95 "MissingSectionHeaderError", "ConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000096 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000097
Guido van Rossum3d209861997-12-09 16:10:31 +000098DEFAULTSECT = "DEFAULT"
99
Fred Drake2a37f9f2000-09-27 22:43:54 +0000100MAX_INTERPOLATION_DEPTH = 10
101
Guido van Rossum3d209861997-12-09 16:10:31 +0000102
Tim Peters88869f92001-01-14 23:36:06 +0000103
Guido van Rossum3d209861997-12-09 16:10:31 +0000104# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000105class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000106 """Base class for ConfigParser exceptions."""
107
Guido van Rossum3d209861997-12-09 16:10:31 +0000108 def __init__(self, msg=''):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000109 self._msg = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000110 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000111
Guido van Rossum3d209861997-12-09 16:10:31 +0000112 def __repr__(self):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000113 return self._msg
Fred Drake8d5dd982002-12-30 23:51:45 +0000114
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000115 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000116
117class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000118 """Raised when no section matches a requested option."""
119
Guido van Rossum3d209861997-12-09 16:10:31 +0000120 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000121 Error.__init__(self, 'No section: %s' % section)
122 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000123
124class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000125 """Raised when a section is multiply-created."""
126
Guido van Rossum3d209861997-12-09 16:10:31 +0000127 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000128 Error.__init__(self, "Section %s already exists" % section)
129 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000130
131class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000132 """A requested option was not found."""
133
Guido van Rossum3d209861997-12-09 16:10:31 +0000134 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 Error.__init__(self, "No option `%s' in section: %s" %
136 (option, section))
137 self.option = option
138 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000139
140class InterpolationError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000141 """A string substitution required a setting which was not available."""
142
Barry Warsaw64462121998-08-06 18:48:41 +0000143 def __init__(self, reference, option, section, rawval):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 Error.__init__(self,
Barry Warsaw64462121998-08-06 18:48:41 +0000145 "Bad value substitution:\n"
146 "\tsection: [%s]\n"
147 "\toption : %s\n"
148 "\tkey : %s\n"
149 "\trawval : %s\n"
150 % (section, option, reference, rawval))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 self.reference = reference
152 self.option = option
153 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000154
Fred Drake8d5dd982002-12-30 23:51:45 +0000155class InterpolationSyntaxError(Error):
156 """Raised when the source text into which substitutions are made
157 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000158
Fred Drake2a37f9f2000-09-27 22:43:54 +0000159class InterpolationDepthError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000160 """Raised when substitutions are nested too deeply."""
161
Fred Drake2a37f9f2000-09-27 22:43:54 +0000162 def __init__(self, option, section, rawval):
163 Error.__init__(self,
164 "Value interpolation too deeply recursive:\n"
165 "\tsection: [%s]\n"
166 "\toption : %s\n"
167 "\trawval : %s\n"
168 % (section, option, rawval))
169 self.option = option
170 self.section = section
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000171
172class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000173 """Raised when a configuration file does not follow legal syntax."""
174
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000175 def __init__(self, filename):
176 Error.__init__(self, 'File contains parsing errors: %s' % filename)
177 self.filename = filename
178 self.errors = []
179
180 def append(self, lineno, line):
181 self.errors.append((lineno, line))
182 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
183
Fred Drake2a37f9f2000-09-27 22:43:54 +0000184class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000185 """Raised when a key-value pair is found before any section header."""
186
Fred Drake2a37f9f2000-09-27 22:43:54 +0000187 def __init__(self, filename, lineno, line):
188 Error.__init__(
189 self,
190 'File contains no section headers.\nfile: %s, line: %d\n%s' %
191 (filename, lineno, line))
192 self.filename = filename
193 self.lineno = lineno
194 self.line = line
195
Guido van Rossum3d209861997-12-09 16:10:31 +0000196
Tim Peters88869f92001-01-14 23:36:06 +0000197
Fred Drakefce65572002-10-25 18:08:18 +0000198class RawConfigParser:
Guido van Rossum3d209861997-12-09 16:10:31 +0000199 def __init__(self, defaults=None):
Fred Drakefce65572002-10-25 18:08:18 +0000200 self._sections = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000201 if defaults is None:
Fred Drakefce65572002-10-25 18:08:18 +0000202 self._defaults = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000203 else:
Fred Drakefce65572002-10-25 18:08:18 +0000204 self._defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000205
206 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000207 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000208
209 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000211 # self._sections will never have [DEFAULT] in it
212 return self._sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000213
214 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000215 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000216
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000217 Raise DuplicateSectionError if a section by the specified name
218 already exists.
219 """
Fred Drakefce65572002-10-25 18:08:18 +0000220 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 raise DuplicateSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000222 self._sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000223
224 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000225 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000226
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000227 The DEFAULT section is not acknowledged.
228 """
Fred Drakefce65572002-10-25 18:08:18 +0000229 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000230
231 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000232 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000233 try:
Fred Drakefce65572002-10-25 18:08:18 +0000234 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 except KeyError:
236 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000237 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000238 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000239 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000241
242 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000243 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000244
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000245 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000246 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000247 configuration file locations (e.g. current directory, user's
248 home directory, systemwide directory), and all existing
249 configuration files in the list will be read. A single
250 filename may also be given.
251 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000252 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000254 for filename in filenames:
255 try:
256 fp = open(filename)
257 except IOError:
258 continue
Fred Drakefce65572002-10-25 18:08:18 +0000259 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000260 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000261
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000262 def readfp(self, fp, filename=None):
263 """Like read() but the argument must be a file-like object.
264
265 The `fp' argument must have a `readline' method. Optional
266 second argument is the `filename', which if not given, is
267 taken from fp.name. If fp has no `name' attribute, `<???>' is
268 used.
269
270 """
271 if filename is None:
272 try:
273 filename = fp.name
274 except AttributeError:
275 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000276 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000277
Fred Drakefce65572002-10-25 18:08:18 +0000278 def get(self, section, option):
279 opt = self.optionxform(option)
280 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000281 if section != DEFAULTSECT:
282 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000283 if opt in self._defaults:
284 return self._defaults[opt]
285 else:
286 raise NoOptionError(option, section)
287 elif opt in self._sections[section]:
288 return self._sections[section][opt]
289 elif opt in self._defaults:
290 return self._defaults[opt]
291 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000292 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000293
Fred Drakefce65572002-10-25 18:08:18 +0000294 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000295 try:
Fred Drakefce65572002-10-25 18:08:18 +0000296 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000297 except KeyError:
298 if section != DEFAULTSECT:
299 raise NoSectionError(section)
Fred Drakedf393bd2002-10-25 20:41:30 +0000300 d2 = {}
Fred Drakefce65572002-10-25 18:08:18 +0000301 d = self._defaults.copy()
302 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000303 if "__name__" in d:
304 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000305 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000306
Fred Drakefce65572002-10-25 18:08:18 +0000307 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000308 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000309
310 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000311 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000312
313 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000314 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000315
Fred Drakec2ff9052002-09-27 15:33:11 +0000316 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
317 '0': False, 'no': False, 'false': False, 'off': False}
318
Guido van Rossum3d209861997-12-09 16:10:31 +0000319 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000320 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000321 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000322 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000323 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000324
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000325 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000326 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000327
Eric S. Raymond417c4892000-07-10 18:11:00 +0000328 def has_option(self, section, option):
329 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000330 if not section or section == DEFAULTSECT:
331 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000332 return option in self._defaults
333 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000334 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000335 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000336 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000337 return (option in self._sections[section]
338 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000339
340 def set(self, section, option, value):
341 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000342 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000343 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000344 else:
345 try:
Fred Drakefce65572002-10-25 18:08:18 +0000346 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000347 except KeyError:
348 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000349 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000350
351 def write(self, fp):
352 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000353 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000354 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000355 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000356 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000357 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000358 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000359 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000360 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000361 if key != "__name__":
362 fp.write("%s = %s\n" %
363 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000364 fp.write("\n")
365
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000366 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000367 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000368 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000369 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000370 else:
371 try:
Fred Drakefce65572002-10-25 18:08:18 +0000372 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000373 except KeyError:
374 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000375 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000376 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000377 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000378 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000379 return existed
380
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000381 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000382 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000383 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000384 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000385 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000386 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000387
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000388 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000389 # Regular expressions for parsing section headers and options.
390 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000391 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000392 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000393 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000394 r'\]' # ]
395 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000396 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000397 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000398 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000399 # followed by separator
400 # (either : or =), followed
401 # by any # space/tab
402 r'(?P<value>.*)$' # everything up to eol
403 )
404
Fred Drakefce65572002-10-25 18:08:18 +0000405 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000407
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 The sections in setup file contains a title line at the top,
409 indicated by a name in square brackets (`[]'), plus key/value
410 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000411 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000412 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000413 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000414 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000415 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000416 optname = None
417 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000418 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000419 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000420 line = fp.readline()
421 if not line:
422 break
423 lineno = lineno + 1
424 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000425 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 continue
Fred Drake176916a2002-09-27 16:21:18 +0000427 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
428 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000429 continue
430 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000431 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000432 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000433 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000434 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000435 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000437 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000438 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000439 if mo:
440 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000441 if sectname in self._sections:
442 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000443 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000444 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000445 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000446 cursect = {'__name__': sectname}
Fred Drakefce65572002-10-25 18:08:18 +0000447 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000448 # So sections can't start with a continuation line
449 optname = None
450 # no section header in the file?
451 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000452 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000453 # an option line?
454 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000455 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000456 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000457 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000458 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000459 # ';' is a comment delimiter only if it follows
460 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000461 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000462 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000463 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000464 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000465 # allow empty values
466 if optval == '""':
467 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000468 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000469 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000470 else:
471 # a non-fatal parsing error occurred. set up the
472 # exception but keep going. the exception will be
473 # raised at the end of the file and will contain a
474 # list of all bogus lines
475 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000476 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000477 e.append(lineno, `line`)
478 # if any parsing errors occurred, raise an exception
479 if e:
480 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000481
482
483class ConfigParser(RawConfigParser):
484
Neal Norwitzf680cc42002-12-17 01:56:47 +0000485 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000486 """Get an option value for a given section.
487
488 All % interpolations are expanded in the return values, based on the
489 defaults passed into the constructor, unless the optional argument
490 `raw' is true. Additional substitutions may be provided using the
491 `vars' argument, which must be a dictionary whose contents overrides
492 any pre-existing defaults.
493
494 The section DEFAULT is special.
495 """
496 d = self._defaults.copy()
497 try:
498 d.update(self._sections[section])
499 except KeyError:
500 if section != DEFAULTSECT:
501 raise NoSectionError(section)
502 # Update with the entry specific variables
503 if vars is not None:
504 d.update(vars)
505 option = self.optionxform(option)
506 try:
507 value = d[option]
508 except KeyError:
509 raise NoOptionError(option, section)
510
511 if raw:
512 return value
513 else:
514 return self._interpolate(section, option, value, d)
515
Neal Norwitzf680cc42002-12-17 01:56:47 +0000516 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000517 """Return a list of tuples with (name, value) for each option
518 in the section.
519
520 All % interpolations are expanded in the return values, based on the
521 defaults passed into the constructor, unless the optional argument
522 `raw' is true. Additional substitutions may be provided using the
523 `vars' argument, which must be a dictionary whose contents overrides
524 any pre-existing defaults.
525
526 The section DEFAULT is special.
527 """
528 d = self._defaults.copy()
529 try:
530 d.update(self._sections[section])
531 except KeyError:
532 if section != DEFAULTSECT:
533 raise NoSectionError(section)
534 # Update with the entry specific variables
535 if vars:
536 d.update(vars)
Fred Drakedf393bd2002-10-25 20:41:30 +0000537 options = d.keys()
538 if "__name__" in options:
539 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000540 if raw:
Fred Drakedf393bd2002-10-25 20:41:30 +0000541 for option in options:
Fred Drakefce65572002-10-25 18:08:18 +0000542 yield (option, d[option])
543 else:
Fred Drakedf393bd2002-10-25 20:41:30 +0000544 for option in options:
Fred Drakefce65572002-10-25 18:08:18 +0000545 yield (option,
546 self._interpolate(section, option, d[option], d))
547
548 def _interpolate(self, section, option, rawval, vars):
549 # do the string interpolation
550 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000551 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000552 while depth: # Loop through this until it's done
553 depth -= 1
554 if value.find("%(") != -1:
555 try:
556 value = value % vars
Fred Drake00dc5a92002-12-31 06:55:41 +0000557 except KeyError, e:
558 raise InterpolationError(e[0], option, section, rawval)
Fred Drakefce65572002-10-25 18:08:18 +0000559 else:
560 break
561 if value.find("%(") != -1:
562 raise InterpolationDepthError(option, section, rawval)
563 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000564
565
566class SafeConfigParser(ConfigParser):
567
568 def _interpolate(self, section, option, rawval, vars):
569 # do the string interpolation
570 L = []
571 self._interpolate_some(option, L, rawval, section, vars, 1)
572 return ''.join(L)
573
574 _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
575
576 def _interpolate_some(self, option, accum, rest, section, map, depth):
577 if depth > MAX_INTERPOLATION_DEPTH:
578 raise InterpolationDepthError(option, section, rest)
579 while rest:
580 p = rest.find("%")
581 if p < 0:
582 accum.append(rest)
583 return
584 if p > 0:
585 accum.append(rest[:p])
586 rest = rest[p:]
587 # p is no longer used
588 c = rest[1:2]
589 if c == "%":
590 accum.append("%")
591 rest = rest[2:]
592 elif c == "(":
593 m = self._interpvar_match(rest)
594 if m is None:
595 raise InterpolationSyntaxError(
596 "bad interpolation variable syntax at: %r" % rest)
597 var = m.group(1)
598 rest = rest[m.end():]
599 try:
600 v = map[var]
601 except KeyError:
Fred Drake00dc5a92002-12-31 06:55:41 +0000602 raise InterpolationError(var, option, section, rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000603 if "%" in v:
604 self._interpolate_some(option, accum, v,
605 section, map, depth + 1)
606 else:
607 accum.append(v)
608 else:
609 raise InterpolationSyntaxError(
610 "'%' must be followed by '%' or '('")