blob: 845886b7a1dd58ec0d63d2f42d6dc482ef4e0322 [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
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000092__all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",
93 "InterpolationError","InterpolationDepthError","ParsingError",
94 "MissingSectionHeaderError","ConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000095 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000096
Guido van Rossum3d209861997-12-09 16:10:31 +000097DEFAULTSECT = "DEFAULT"
98
Fred Drake2a37f9f2000-09-27 22:43:54 +000099MAX_INTERPOLATION_DEPTH = 10
100
Guido van Rossum3d209861997-12-09 16:10:31 +0000101
Tim Peters88869f92001-01-14 23:36:06 +0000102
Guido van Rossum3d209861997-12-09 16:10:31 +0000103# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000104class Error(Exception):
Guido van Rossum3d209861997-12-09 16:10:31 +0000105 def __init__(self, msg=''):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000106 self._msg = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000107 Exception.__init__(self, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000108 def __repr__(self):
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000109 return self._msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000110 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000111
112class NoSectionError(Error):
113 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000114 Error.__init__(self, 'No section: %s' % section)
115 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000116
117class DuplicateSectionError(Error):
118 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000119 Error.__init__(self, "Section %s already exists" % section)
120 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000121
122class NoOptionError(Error):
123 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000124 Error.__init__(self, "No option `%s' in section: %s" %
125 (option, section))
126 self.option = option
127 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000128
129class InterpolationError(Error):
Barry Warsaw64462121998-08-06 18:48:41 +0000130 def __init__(self, reference, option, section, rawval):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000131 Error.__init__(self,
Barry Warsaw64462121998-08-06 18:48:41 +0000132 "Bad value substitution:\n"
133 "\tsection: [%s]\n"
134 "\toption : %s\n"
135 "\tkey : %s\n"
136 "\trawval : %s\n"
137 % (section, option, reference, rawval))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000138 self.reference = reference
139 self.option = option
140 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000141
Fred Drake2a37f9f2000-09-27 22:43:54 +0000142class InterpolationDepthError(Error):
143 def __init__(self, option, section, rawval):
144 Error.__init__(self,
145 "Value interpolation too deeply recursive:\n"
146 "\tsection: [%s]\n"
147 "\toption : %s\n"
148 "\trawval : %s\n"
149 % (section, option, rawval))
150 self.option = option
151 self.section = section
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000152
153class ParsingError(Error):
154 def __init__(self, filename):
155 Error.__init__(self, 'File contains parsing errors: %s' % filename)
156 self.filename = filename
157 self.errors = []
158
159 def append(self, lineno, line):
160 self.errors.append((lineno, line))
161 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
162
Fred Drake2a37f9f2000-09-27 22:43:54 +0000163class MissingSectionHeaderError(ParsingError):
164 def __init__(self, filename, lineno, line):
165 Error.__init__(
166 self,
167 'File contains no section headers.\nfile: %s, line: %d\n%s' %
168 (filename, lineno, line))
169 self.filename = filename
170 self.lineno = lineno
171 self.line = line
172
Guido van Rossum3d209861997-12-09 16:10:31 +0000173
Tim Peters88869f92001-01-14 23:36:06 +0000174
Fred Drakefce65572002-10-25 18:08:18 +0000175class RawConfigParser:
Guido van Rossum3d209861997-12-09 16:10:31 +0000176 def __init__(self, defaults=None):
Fred Drakefce65572002-10-25 18:08:18 +0000177 self._sections = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 if defaults is None:
Fred Drakefce65572002-10-25 18:08:18 +0000179 self._defaults = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000180 else:
Fred Drakefce65572002-10-25 18:08:18 +0000181 self._defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000182
183 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000184 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000185
186 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000187 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000188 # self._sections will never have [DEFAULT] in it
189 return self._sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000190
191 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000193
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 Raise DuplicateSectionError if a section by the specified name
195 already exists.
196 """
Fred Drakefce65572002-10-25 18:08:18 +0000197 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 raise DuplicateSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000199 self._sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000200
201 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000203
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 The DEFAULT section is not acknowledged.
205 """
Fred Drakefce65572002-10-25 18:08:18 +0000206 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000207
208 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000209 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 try:
Fred Drakefce65572002-10-25 18:08:18 +0000211 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 except KeyError:
213 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000214 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000215 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000216 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000217 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000218
219 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000220 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000221
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000222 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000223 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000224 configuration file locations (e.g. current directory, user's
225 home directory, systemwide directory), and all existing
226 configuration files in the list will be read. A single
227 filename may also be given.
228 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000229 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 filenames = [filenames]
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000231 for filename in filenames:
232 try:
233 fp = open(filename)
234 except IOError:
235 continue
Fred Drakefce65572002-10-25 18:08:18 +0000236 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000237 fp.close()
Guido van Rossum3d209861997-12-09 16:10:31 +0000238
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000239 def readfp(self, fp, filename=None):
240 """Like read() but the argument must be a file-like object.
241
242 The `fp' argument must have a `readline' method. Optional
243 second argument is the `filename', which if not given, is
244 taken from fp.name. If fp has no `name' attribute, `<???>' is
245 used.
246
247 """
248 if filename is None:
249 try:
250 filename = fp.name
251 except AttributeError:
252 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000253 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000254
Fred Drakefce65572002-10-25 18:08:18 +0000255 def get(self, section, option):
256 opt = self.optionxform(option)
257 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000258 if section != DEFAULTSECT:
259 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000260 if opt in self._defaults:
261 return self._defaults[opt]
262 else:
263 raise NoOptionError(option, section)
264 elif opt in self._sections[section]:
265 return self._sections[section][opt]
266 elif opt in self._defaults:
267 return self._defaults[opt]
268 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000270
Fred Drakefce65572002-10-25 18:08:18 +0000271 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000272 try:
Fred Drakefce65572002-10-25 18:08:18 +0000273 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000274 except KeyError:
275 if section != DEFAULTSECT:
276 raise NoSectionError(section)
Fred Drakedf393bd2002-10-25 20:41:30 +0000277 d2 = {}
Fred Drakefce65572002-10-25 18:08:18 +0000278 d = self._defaults.copy()
279 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000280 if "__name__" in d:
281 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000282 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000283
Fred Drakefce65572002-10-25 18:08:18 +0000284 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000286
287 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000288 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000289
290 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000291 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000292
Fred Drakec2ff9052002-09-27 15:33:11 +0000293 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
294 '0': False, 'no': False, 'false': False, 'off': False}
295
Guido van Rossum3d209861997-12-09 16:10:31 +0000296 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000297 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000298 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000299 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000300 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000301
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000302 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000303 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000304
Eric S. Raymond417c4892000-07-10 18:11:00 +0000305 def has_option(self, section, option):
306 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000307 if not section or section == DEFAULTSECT:
308 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000309 return option in self._defaults
310 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000311 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000312 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000313 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000314 return (option in self._sections[section]
315 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000316
317 def set(self, section, option, value):
318 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000319 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000320 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000321 else:
322 try:
Fred Drakefce65572002-10-25 18:08:18 +0000323 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000324 except KeyError:
325 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000326 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000327
328 def write(self, fp):
329 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000330 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000331 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000332 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000333 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000334 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000335 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000336 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000337 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000338 if key != "__name__":
339 fp.write("%s = %s\n" %
340 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000341 fp.write("\n")
342
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000343 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000344 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000345 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000346 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000347 else:
348 try:
Fred Drakefce65572002-10-25 18:08:18 +0000349 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000350 except KeyError:
351 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000352 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000353 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000354 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000355 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000356 return existed
357
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000358 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000359 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000360 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000361 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000362 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000363 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000364
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000365 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000366 # Regular expressions for parsing section headers and options.
367 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000368 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000369 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000370 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000371 r'\]' # ]
372 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000373 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000374 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000375 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000376 # followed by separator
377 # (either : or =), followed
378 # by any # space/tab
379 r'(?P<value>.*)$' # everything up to eol
380 )
381
Fred Drakefce65572002-10-25 18:08:18 +0000382 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000383 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000384
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000385 The sections in setup file contains a title line at the top,
386 indicated by a name in square brackets (`[]'), plus key/value
387 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000388 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000389 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000390 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000392 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000393 optname = None
394 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000395 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000396 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000397 line = fp.readline()
398 if not line:
399 break
400 lineno = lineno + 1
401 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000402 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000403 continue
Fred Drake176916a2002-09-27 16:21:18 +0000404 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
405 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 continue
407 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000408 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000409 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000411 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000412 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000413 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000414 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000415 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000416 if mo:
417 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000418 if sectname in self._sections:
419 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000420 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000421 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000422 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000423 cursect = {'__name__': sectname}
Fred Drakefce65572002-10-25 18:08:18 +0000424 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000425 # So sections can't start with a continuation line
426 optname = None
427 # no section header in the file?
428 elif cursect is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000429 raise MissingSectionHeaderError(fpname, lineno, `line`)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000430 # an option line?
431 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000432 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000433 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000434 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000435 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000436 # ';' is a comment delimiter only if it follows
437 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000438 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000439 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000440 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000441 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000442 # allow empty values
443 if optval == '""':
444 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000445 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000446 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000447 else:
448 # a non-fatal parsing error occurred. set up the
449 # exception but keep going. the exception will be
450 # raised at the end of the file and will contain a
451 # list of all bogus lines
452 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000453 e = ParsingError(fpname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000454 e.append(lineno, `line`)
455 # if any parsing errors occurred, raise an exception
456 if e:
457 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000458
459
460class ConfigParser(RawConfigParser):
461
Neal Norwitzf680cc42002-12-17 01:56:47 +0000462 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000463 """Get an option value for a given section.
464
465 All % interpolations are expanded in the return values, based on the
466 defaults passed into the constructor, unless the optional argument
467 `raw' is true. Additional substitutions may be provided using the
468 `vars' argument, which must be a dictionary whose contents overrides
469 any pre-existing defaults.
470
471 The section DEFAULT is special.
472 """
473 d = self._defaults.copy()
474 try:
475 d.update(self._sections[section])
476 except KeyError:
477 if section != DEFAULTSECT:
478 raise NoSectionError(section)
479 # Update with the entry specific variables
480 if vars is not None:
481 d.update(vars)
482 option = self.optionxform(option)
483 try:
484 value = d[option]
485 except KeyError:
486 raise NoOptionError(option, section)
487
488 if raw:
489 return value
490 else:
491 return self._interpolate(section, option, value, d)
492
Neal Norwitzf680cc42002-12-17 01:56:47 +0000493 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000494 """Return a list of tuples with (name, value) for each option
495 in the section.
496
497 All % interpolations are expanded in the return values, based on the
498 defaults passed into the constructor, unless the optional argument
499 `raw' is true. Additional substitutions may be provided using the
500 `vars' argument, which must be a dictionary whose contents overrides
501 any pre-existing defaults.
502
503 The section DEFAULT is special.
504 """
505 d = self._defaults.copy()
506 try:
507 d.update(self._sections[section])
508 except KeyError:
509 if section != DEFAULTSECT:
510 raise NoSectionError(section)
511 # Update with the entry specific variables
512 if vars:
513 d.update(vars)
Fred Drakedf393bd2002-10-25 20:41:30 +0000514 options = d.keys()
515 if "__name__" in options:
516 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000517 if raw:
Fred Drakedf393bd2002-10-25 20:41:30 +0000518 for option in options:
Fred Drakefce65572002-10-25 18:08:18 +0000519 yield (option, d[option])
520 else:
Fred Drakedf393bd2002-10-25 20:41:30 +0000521 for option in options:
Fred Drakefce65572002-10-25 18:08:18 +0000522 yield (option,
523 self._interpolate(section, option, d[option], d))
524
525 def _interpolate(self, section, option, rawval, vars):
526 # do the string interpolation
527 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000528 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000529 while depth: # Loop through this until it's done
530 depth -= 1
531 if value.find("%(") != -1:
532 try:
533 value = value % vars
534 except KeyError, key:
535 raise InterpolationError(key, option, section, rawval)
536 else:
537 break
538 if value.find("%(") != -1:
539 raise InterpolationDepthError(option, section, rawval)
540 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000541
542
543class SafeConfigParser(ConfigParser):
544
545 def _interpolate(self, section, option, rawval, vars):
546 # do the string interpolation
547 L = []
548 self._interpolate_some(option, L, rawval, section, vars, 1)
549 return ''.join(L)
550
551 _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
552
553 def _interpolate_some(self, option, accum, rest, section, map, depth):
554 if depth > MAX_INTERPOLATION_DEPTH:
555 raise InterpolationDepthError(option, section, rest)
556 while rest:
557 p = rest.find("%")
558 if p < 0:
559 accum.append(rest)
560 return
561 if p > 0:
562 accum.append(rest[:p])
563 rest = rest[p:]
564 # p is no longer used
565 c = rest[1:2]
566 if c == "%":
567 accum.append("%")
568 rest = rest[2:]
569 elif c == "(":
570 m = self._interpvar_match(rest)
571 if m is None:
572 raise InterpolationSyntaxError(
573 "bad interpolation variable syntax at: %r" % rest)
574 var = m.group(1)
575 rest = rest[m.end():]
576 try:
577 v = map[var]
578 except KeyError:
579 raise InterpolationError(
580 "no value found for %r" % var)
581 if "%" in v:
582 self._interpolate_some(option, accum, v,
583 section, map, depth + 1)
584 else:
585 accum.append(v)
586 else:
587 raise InterpolationSyntaxError(
588 "'%' must be followed by '%' or '('")