blob: 327f9ea86ffc1876df317b691910fe2e23f85103 [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
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)
Guido van Rossumfb06f752001-10-04 19:58:46 +000069 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.
Eric S. Raymond649685a2000-07-14 14:28:22 +000072
73 remove_section(section)
Tim Peters88869f92001-01-14 23:36:06 +000074 remove the given file section and all its options
Eric S. Raymond649685a2000-07-14 14:28:22 +000075
76 remove_option(section, option)
Tim Peters88869f92001-01-14 23:36:06 +000077 remove the given option from the given section
Eric S. Raymond649685a2000-07-14 14:28:22 +000078
79 set(section, option, value)
80 set the given option
81
82 write(fp)
Tim Peters88869f92001-01-14 23:36:06 +000083 write the configuration state in .ini format
Guido van Rossum3d209861997-12-09 16:10:31 +000084"""
85
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000086import re
Guido van Rossum3d209861997-12-09 16:10:31 +000087
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000088__all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",
89 "InterpolationError","InterpolationDepthError","ParsingError",
90 "MissingSectionHeaderError","ConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000091 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000092
Guido van Rossum3d209861997-12-09 16:10:31 +000093DEFAULTSECT = "DEFAULT"
94
Fred Drake2a37f9f2000-09-27 22:43:54 +000095MAX_INTERPOLATION_DEPTH = 10
96
Guido van Rossum3d209861997-12-09 16:10:31 +000097
Tim Peters88869f92001-01-14 23:36:06 +000098
Guido van Rossum3d209861997-12-09 16:10:31 +000099# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000100class Error(Exception):
Guido van Rossum3d209861997-12-09 16:10:31 +0000101 def __init__(self, msg=''):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000102 self._msg = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000103 Exception.__init__(self, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000104 def __repr__(self):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000105 return self._msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000106 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000107
108class NoSectionError(Error):
109 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000110 Error.__init__(self, 'No section: %s' % section)
111 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000112
113class DuplicateSectionError(Error):
114 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000115 Error.__init__(self, "Section %s already exists" % section)
116 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000117
118class NoOptionError(Error):
119 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000120 Error.__init__(self, "No option `%s' in section: %s" %
121 (option, section))
122 self.option = option
123 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000124
125class InterpolationError(Error):
Barry Warsaw64462121998-08-06 18:48:41 +0000126 def __init__(self, reference, option, section, rawval):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000127 Error.__init__(self,
Barry Warsaw64462121998-08-06 18:48:41 +0000128 "Bad value substitution:\n"
129 "\tsection: [%s]\n"
130 "\toption : %s\n"
131 "\tkey : %s\n"
132 "\trawval : %s\n"
133 % (section, option, reference, rawval))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000134 self.reference = reference
135 self.option = option
136 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000137
Fred Drake2a37f9f2000-09-27 22:43:54 +0000138class InterpolationDepthError(Error):
139 def __init__(self, option, section, rawval):
140 Error.__init__(self,
141 "Value interpolation too deeply recursive:\n"
142 "\tsection: [%s]\n"
143 "\toption : %s\n"
144 "\trawval : %s\n"
145 % (section, option, rawval))
146 self.option = option
147 self.section = section
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000148
149class ParsingError(Error):
150 def __init__(self, filename):
151 Error.__init__(self, 'File contains parsing errors: %s' % filename)
152 self.filename = filename
153 self.errors = []
154
155 def append(self, lineno, line):
156 self.errors.append((lineno, line))
157 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
158
Fred Drake2a37f9f2000-09-27 22:43:54 +0000159class MissingSectionHeaderError(ParsingError):
160 def __init__(self, filename, lineno, line):
161 Error.__init__(
162 self,
163 'File contains no section headers.\nfile: %s, line: %d\n%s' %
164 (filename, lineno, line))
165 self.filename = filename
166 self.lineno = lineno
167 self.line = line
168
Guido van Rossum3d209861997-12-09 16:10:31 +0000169
Tim Peters88869f92001-01-14 23:36:06 +0000170
Guido van Rossum3d209861997-12-09 16:10:31 +0000171class ConfigParser:
172 def __init__(self, defaults=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 self.__sections = {}
174 if defaults is None:
175 self.__defaults = {}
176 else:
177 self.__defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000178
179 def defaults(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 return self.__defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000181
182 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000183 """Return a list of section names, excluding [DEFAULT]"""
184 # self.__sections will never have [DEFAULT] in it
185 return self.__sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000186
187 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000188 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000189
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 Raise DuplicateSectionError if a section by the specified name
191 already exists.
192 """
Raymond Hettinger54f02222002-06-01 14:18:47 +0000193 if section in self.__sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 raise DuplicateSectionError(section)
195 self.__sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000196
197 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000199
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 The DEFAULT section is not acknowledged.
201 """
Fred Drakec2ff9052002-09-27 15:33:11 +0000202 return section in self.__sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000203
204 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000205 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 try:
207 opts = self.__sections[section].copy()
208 except KeyError:
209 raise NoSectionError(section)
210 opts.update(self.__defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000211 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000212 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000214
215 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000216 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000217
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000218 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000219 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000220 configuration file locations (e.g. current directory, user's
221 home directory, systemwide directory), and all existing
222 configuration files in the list will be read. A single
223 filename may also be given.
224 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000225 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000227 for filename in filenames:
228 try:
229 fp = open(filename)
230 except IOError:
231 continue
232 self.__read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000233 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000234
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000235 def readfp(self, fp, filename=None):
236 """Like read() but the argument must be a file-like object.
237
238 The `fp' argument must have a `readline' method. Optional
239 second argument is the `filename', which if not given, is
240 taken from fp.name. If fp has no `name' attribute, `<???>' is
241 used.
242
243 """
244 if filename is None:
245 try:
246 filename = fp.name
247 except AttributeError:
248 filename = '<???>'
249 self.__read(fp, filename)
250
Guido van Rossume6506e71999-01-26 19:29:25 +0000251 def get(self, section, option, raw=0, vars=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 """Get an option value for a given section.
Guido van Rossum3d209861997-12-09 16:10:31 +0000253
Barry Warsawf09f6a51999-01-26 22:01:37 +0000254 All % interpolations are expanded in the return values, based on the
255 defaults passed into the constructor, unless the optional argument
256 `raw' is true. Additional substitutions may be provided using the
257 `vars' argument, which must be a dictionary whose contents overrides
258 any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +0000259
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 The section DEFAULT is special.
261 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000262 d = self.__defaults.copy()
Fred Drakec2ff9052002-09-27 15:33:11 +0000263 try:
264 d.update(self.__sections[section])
265 except KeyError:
266 if section != DEFAULTSECT:
267 raise NoSectionError(section)
Guido van Rossume6506e71999-01-26 19:29:25 +0000268 # Update with the entry specific variables
Raymond Hettinger0f4940c2002-06-01 00:57:55 +0000269 if vars is not None:
Guido van Rossume6506e71999-01-26 19:29:25 +0000270 d.update(vars)
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000271 option = self.optionxform(option)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000272 try:
Fred Drakec2ff9052002-09-27 15:33:11 +0000273 value = d[option]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000274 except KeyError:
275 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000276
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000277 if raw:
Fred Drakec2ff9052002-09-27 15:33:11 +0000278 return value
279 return self._interpolate(section, option, value, d)
Guido van Rossum3d209861997-12-09 16:10:31 +0000280
Fred Drakec2ff9052002-09-27 15:33:11 +0000281 def _interpolate(self, section, option, rawval, vars):
Fred Drake2a37f9f2000-09-27 22:43:54 +0000282 # do the string interpolation
Fred Drakec2ff9052002-09-27 15:33:11 +0000283 value = rawval
284 depth = MAX_INTERPOLATION_DEPTH
285 while depth: # Loop through this until it's done
286 depth -= 1
287 if value.find("%(") != -1:
Guido van Rossume6506e71999-01-26 19:29:25 +0000288 try:
Fred Drakec2ff9052002-09-27 15:33:11 +0000289 value = value % vars
Guido van Rossume6506e71999-01-26 19:29:25 +0000290 except KeyError, key:
291 raise InterpolationError(key, option, section, rawval)
292 else:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000293 break
Fred Drakec2ff9052002-09-27 15:33:11 +0000294 if value.find("%(") != -1:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000295 raise InterpolationDepthError(option, section, rawval)
296 return value
Tim Peters88869f92001-01-14 23:36:06 +0000297
Guido van Rossum3d209861997-12-09 16:10:31 +0000298 def __get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000299 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000300
301 def getint(self, section, option):
Fred Draked451ec12002-04-26 02:29:55 +0000302 return self.__get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000303
304 def getfloat(self, section, option):
Fred Draked451ec12002-04-26 02:29:55 +0000305 return self.__get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000306
Fred Drakec2ff9052002-09-27 15:33:11 +0000307 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
308 '0': False, 'no': False, 'false': False, 'off': False}
309
Guido van Rossum3d209861997-12-09 16:10:31 +0000310 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000311 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000312 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000313 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000314 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000315
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000316 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000317 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000318
Eric S. Raymond417c4892000-07-10 18:11:00 +0000319 def has_option(self, section, option):
320 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000321 if not section or section == DEFAULTSECT:
322 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000323 return option in self.__defaults
Fred Drakec2ff9052002-09-27 15:33:11 +0000324 elif section not in self.__sections:
Eric S. Raymond417c4892000-07-10 18:11:00 +0000325 return 0
326 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000327 option = self.optionxform(option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000328 return (option in self.__sections[section]
329 or option in self.__defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000330
331 def set(self, section, option, value):
332 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000333 if not section or section == DEFAULTSECT:
Eric S. Raymond417c4892000-07-10 18:11:00 +0000334 sectdict = self.__defaults
335 else:
336 try:
337 sectdict = self.__sections[section]
338 except KeyError:
339 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000340 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000341
342 def write(self, fp):
343 """Write an .ini-format representation of the configuration state."""
344 if self.__defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000345 fp.write("[%s]\n" % DEFAULTSECT)
Eric S. Raymond649685a2000-07-14 14:28:22 +0000346 for (key, value) in self.__defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000347 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000348 fp.write("\n")
Fred Drakec2ff9052002-09-27 15:33:11 +0000349 for section in self.__sections:
350 fp.write("[%s]\n" % section)
351 for (key, value) in self.__sections[section].items():
352 if key != "__name__":
353 fp.write("%s = %s\n" %
354 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000355 fp.write("\n")
356
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000357 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000358 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000359 if not section or section == DEFAULTSECT:
Eric S. Raymond649685a2000-07-14 14:28:22 +0000360 sectdict = self.__defaults
361 else:
362 try:
363 sectdict = self.__sections[section]
364 except KeyError:
365 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000366 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000367 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000368 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000369 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000370 return existed
371
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000372 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000373 """Remove a file section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000374 existed = section in self.__sections
375 if existed:
Eric S. Raymond649685a2000-07-14 14:28:22 +0000376 del self.__sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000377 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000378
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000379 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000380 # Regular expressions for parsing section headers and options.
381 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000382 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000383 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000384 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000385 r'\]' # ]
386 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000387 OPTCRE = re.compile(
Fred Drakec2ff9052002-09-27 15:33:11 +0000388 r'(?P<option>[^:=\s]+)' # very permissive!
389 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000390 # followed by separator
391 # (either : or =), followed
392 # by any # space/tab
393 r'(?P<value>.*)$' # everything up to eol
394 )
395
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000396 def __read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000397 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000398
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000399 The sections in setup file contains a title line at the top,
400 indicated by a name in square brackets (`[]'), plus key/value
401 options lines, indicated by `name: value' format lines.
402 Continuation are represented by an embedded newline then
403 leading whitespace. Blank lines, lines beginning with a '#',
404 and just about everything else is ignored.
405 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000406 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000407 optname = None
408 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000409 e = None # None, or an exception
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 while 1:
411 line = fp.readline()
412 if not line:
413 break
414 lineno = lineno + 1
415 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000416 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000417 continue
Fred Drakec2ff9052002-09-27 15:33:11 +0000418 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR": # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000419 continue
420 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000421 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000422 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000424 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000425 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000427 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000428 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000429 if mo:
430 sectname = mo.group('header')
Raymond Hettinger54f02222002-06-01 14:18:47 +0000431 if sectname in self.__sections:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000432 cursect = self.__sections[sectname]
433 elif sectname == DEFAULTSECT:
434 cursect = self.__defaults
435 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000436 cursect = {'__name__': sectname}
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000437 self.__sections[sectname] = cursect
438 # So sections can't start with a continuation line
439 optname = None
440 # no section header in the file?
441 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000442 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000443 # an option line?
444 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000445 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000446 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000447 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000448 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000449 # ';' is a comment delimiter only if it follows
450 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000451 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000452 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000453 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000454 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000455 # allow empty values
456 if optval == '""':
457 optval = ''
Fred Drakec2ff9052002-09-27 15:33:11 +0000458 optname = self.optionxform(optname)
459 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000460 else:
461 # a non-fatal parsing error occurred. set up the
462 # exception but keep going. the exception will be
463 # raised at the end of the file and will contain a
464 # list of all bogus lines
465 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000466 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000467 e.append(lineno, `line`)
468 # if any parsing errors occurred, raise an exception
469 if e:
470 raise e