blob: faa0930f432974cf0b5ee3fd3ad1d9f0c793177d [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
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +000022ConfigParser -- responsible for parsing a list of
Guido van Rossum3d209861997-12-09 16:10:31 +000023 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;
Georg Brandl7eb4b7d2005-07-22 21:49:32 +000031 its 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
Fred Drake82903142004-05-18 04:24:02 +000048 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000049
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",
David Goodger1cbf2062004-10-03 15:55:09 +000095 "MissingSectionHeaderError",
96 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000097 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000098
Guido van Rossum3d209861997-12-09 16:10:31 +000099DEFAULTSECT = "DEFAULT"
100
Fred Drake2a37f9f2000-09-27 22:43:54 +0000101MAX_INTERPOLATION_DEPTH = 10
102
Guido van Rossum3d209861997-12-09 16:10:31 +0000103
Tim Peters88869f92001-01-14 23:36:06 +0000104
Guido van Rossum3d209861997-12-09 16:10:31 +0000105# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000106class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000107 """Base class for ConfigParser exceptions."""
108
Guido van Rossum360e4b82007-05-14 22:51:27 +0000109 def _get_message(self):
110 """Getter for 'message'; needed only to override deprecation in
111 BaseException."""
112 return self.__message
113
114 def _set_message(self, value):
115 """Setter for 'message'; needed only to override deprecation in
116 BaseException."""
117 self.__message = value
118
119 # BaseException.message has been deprecated since Python 2.6. To prevent
120 # DeprecationWarning from popping up over this pre-existing attribute, use
121 # a new property that takes lookup precedence.
122 message = property(_get_message, _set_message)
123
Guido van Rossum3d209861997-12-09 16:10:31 +0000124 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000125 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000126 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000127
Guido van Rossum3d209861997-12-09 16:10:31 +0000128 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000129 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000130
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000131 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000132
133class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000134 """Raised when no section matches a requested option."""
135
Guido van Rossum3d209861997-12-09 16:10:31 +0000136 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000137 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000138 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000139
140class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000141 """Raised when a section is multiply-created."""
142
Guido van Rossum3d209861997-12-09 16:10:31 +0000143 def __init__(self, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000144 Error.__init__(self, "Section %r already exists" % section)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000146
147class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000148 """A requested option was not found."""
149
Guido van Rossum3d209861997-12-09 16:10:31 +0000150 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000151 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000152 (option, section))
153 self.option = option
154 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000155
156class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000157 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000158
Fred Drakee2c64912002-12-31 17:23:27 +0000159 def __init__(self, option, section, msg):
160 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 self.option = option
162 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000163
Fred Drakee2c64912002-12-31 17:23:27 +0000164class InterpolationMissingOptionError(InterpolationError):
165 """A string substitution required a setting which was not available."""
166
167 def __init__(self, option, section, rawval, reference):
168 msg = ("Bad value substitution:\n"
169 "\tsection: [%s]\n"
170 "\toption : %s\n"
171 "\tkey : %s\n"
172 "\trawval : %s\n"
173 % (section, option, reference, rawval))
174 InterpolationError.__init__(self, option, section, msg)
175 self.reference = reference
176
177class InterpolationSyntaxError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000178 """Raised when the source text into which substitutions are made
179 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000180
Fred Drakee2c64912002-12-31 17:23:27 +0000181class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000182 """Raised when substitutions are nested too deeply."""
183
Fred Drake2a37f9f2000-09-27 22:43:54 +0000184 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000185 msg = ("Value interpolation too deeply recursive:\n"
186 "\tsection: [%s]\n"
187 "\toption : %s\n"
188 "\trawval : %s\n"
189 % (section, option, rawval))
190 InterpolationError.__init__(self, option, section, msg)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000191
192class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000193 """Raised when a configuration file does not follow legal syntax."""
194
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000195 def __init__(self, filename):
196 Error.__init__(self, 'File contains parsing errors: %s' % filename)
197 self.filename = filename
198 self.errors = []
199
200 def append(self, lineno, line):
201 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000202 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000203
Fred Drake2a37f9f2000-09-27 22:43:54 +0000204class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000205 """Raised when a key-value pair is found before any section header."""
206
Fred Drake2a37f9f2000-09-27 22:43:54 +0000207 def __init__(self, filename, lineno, line):
208 Error.__init__(
209 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000210 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000211 (filename, lineno, line))
212 self.filename = filename
213 self.lineno = lineno
214 self.line = line
215
Guido van Rossum3d209861997-12-09 16:10:31 +0000216
Fred Drakefce65572002-10-25 18:08:18 +0000217class RawConfigParser:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000218 def __init__(self, defaults=None, dict_type=dict):
219 self._dict = dict_type
220 self._sections = self._dict()
221 self._defaults = self._dict()
David Goodger68a1abd2004-10-03 15:40:25 +0000222 if defaults:
223 for key, value in defaults.items():
224 self._defaults[self.optionxform(key)] = value
Guido van Rossum3d209861997-12-09 16:10:31 +0000225
226 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000227 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000228
229 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000231 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000232 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000233
234 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000235 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000236
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 Raise DuplicateSectionError if a section by the specified name
238 already exists.
239 """
Fred Drakefce65572002-10-25 18:08:18 +0000240 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000242 self._sections[section] = self._dict()
Guido van Rossum3d209861997-12-09 16:10:31 +0000243
244 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000246
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000247 The DEFAULT section is not acknowledged.
248 """
Fred Drakefce65572002-10-25 18:08:18 +0000249 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000250
251 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000252 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 try:
Fred Drakefce65572002-10-25 18:08:18 +0000254 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000255 except KeyError:
256 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000257 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000258 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000259 del opts['__name__']
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000260 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000261
262 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000263 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000264
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000265 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000266 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000267 configuration file locations (e.g. current directory, user's
268 home directory, systemwide directory), and all existing
269 configuration files in the list will be read. A single
270 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000271
272 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000273 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000274 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000276 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000277 for filename in filenames:
278 try:
279 fp = open(filename)
280 except IOError:
281 continue
Fred Drakefce65572002-10-25 18:08:18 +0000282 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000283 fp.close()
Fred Drake82903142004-05-18 04:24:02 +0000284 read_ok.append(filename)
285 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000286
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000287 def readfp(self, fp, filename=None):
288 """Like read() but the argument must be a file-like object.
289
290 The `fp' argument must have a `readline' method. Optional
291 second argument is the `filename', which if not given, is
292 taken from fp.name. If fp has no `name' attribute, `<???>' is
293 used.
294
295 """
296 if filename is None:
297 try:
298 filename = fp.name
299 except AttributeError:
300 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000301 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000302
Fred Drakefce65572002-10-25 18:08:18 +0000303 def get(self, section, option):
304 opt = self.optionxform(option)
305 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000306 if section != DEFAULTSECT:
307 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000308 if opt in self._defaults:
309 return self._defaults[opt]
310 else:
311 raise NoOptionError(option, section)
312 elif opt in self._sections[section]:
313 return self._sections[section][opt]
314 elif opt in self._defaults:
315 return self._defaults[opt]
316 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000317 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000318
Fred Drakefce65572002-10-25 18:08:18 +0000319 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000320 try:
Fred Drakefce65572002-10-25 18:08:18 +0000321 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000322 except KeyError:
323 if section != DEFAULTSECT:
324 raise NoSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325 d2 = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000326 d = self._defaults.copy()
327 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000328 if "__name__" in d:
329 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000330 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000331
Fred Drakefce65572002-10-25 18:08:18 +0000332 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000333 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000334
335 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000336 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000337
338 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000339 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000340
Fred Drakec2ff9052002-09-27 15:33:11 +0000341 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
342 '0': False, 'no': False, 'false': False, 'off': False}
343
Guido van Rossum3d209861997-12-09 16:10:31 +0000344 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000345 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000346 if v.lower() not in self._boolean_states:
Collin Winterce36ad82007-08-30 01:19:48 +0000347 raise ValueError('Not a boolean: %s' % v)
Fred Drakec2ff9052002-09-27 15:33:11 +0000348 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000349
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000350 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000351 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000352
Eric S. Raymond417c4892000-07-10 18:11:00 +0000353 def has_option(self, section, option):
354 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000355 if not section or section == DEFAULTSECT:
356 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000357 return option in self._defaults
358 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000359 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000360 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000361 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000362 return (option in self._sections[section]
363 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000364
365 def set(self, section, option, value):
366 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000367 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000368 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000369 else:
370 try:
Fred Drakefce65572002-10-25 18:08:18 +0000371 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000372 except KeyError:
373 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000374 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000375
376 def write(self, fp):
377 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000378 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000379 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000380 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000381 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000382 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000383 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000384 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000385 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000386 if key != "__name__":
387 fp.write("%s = %s\n" %
388 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000389 fp.write("\n")
390
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000391 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000392 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000393 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000394 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000395 else:
396 try:
Fred Drakefce65572002-10-25 18:08:18 +0000397 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000398 except KeyError:
399 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000400 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000401 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000402 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000403 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000404 return existed
405
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000406 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000407 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000408 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000409 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000410 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000411 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000412
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000413 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000414 # Regular expressions for parsing section headers and options.
415 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000416 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000417 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000418 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000419 r'\]' # ]
420 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000421 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000422 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000423 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000424 # followed by separator
425 # (either : or =), followed
426 # by any # space/tab
427 r'(?P<value>.*)$' # everything up to eol
428 )
429
Fred Drakefce65572002-10-25 18:08:18 +0000430 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000431 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000432
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000433 The sections in setup file contains a title line at the top,
434 indicated by a name in square brackets (`[]'), plus key/value
435 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000436 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000437 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000438 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000439 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000440 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000441 optname = None
442 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000443 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000444 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000445 line = fp.readline()
446 if not line:
447 break
448 lineno = lineno + 1
449 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000450 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000451 continue
Fred Drake176916a2002-09-27 16:21:18 +0000452 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
453 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000454 continue
455 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000456 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000457 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000458 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000459 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000460 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000461 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000462 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000463 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000464 if mo:
465 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000466 if sectname in self._sections:
467 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000468 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000469 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000470 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000471 cursect = self._dict()
472 cursect['__name__'] = sectname
Fred Drakefce65572002-10-25 18:08:18 +0000473 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000474 # So sections can't start with a continuation line
475 optname = None
476 # no section header in the file?
477 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000478 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000479 # an option line?
480 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000481 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000482 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000483 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000484 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000485 # ';' is a comment delimiter only if it follows
486 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000487 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000488 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000489 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000490 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000491 # allow empty values
492 if optval == '""':
493 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000494 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000495 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000496 else:
497 # a non-fatal parsing error occurred. set up the
498 # exception but keep going. the exception will be
499 # raised at the end of the file and will contain a
500 # list of all bogus lines
501 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000502 e = ParsingError(fpname)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000503 e.append(lineno, repr(line))
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000504 # if any parsing errors occurred, raise an exception
505 if e:
506 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000507
508
509class ConfigParser(RawConfigParser):
510
Neal Norwitzf680cc42002-12-17 01:56:47 +0000511 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000512 """Get an option value for a given section.
513
514 All % interpolations are expanded in the return values, based on the
515 defaults passed into the constructor, unless the optional argument
516 `raw' is true. Additional substitutions may be provided using the
517 `vars' argument, which must be a dictionary whose contents overrides
518 any pre-existing defaults.
519
520 The section DEFAULT is special.
521 """
522 d = self._defaults.copy()
523 try:
524 d.update(self._sections[section])
525 except KeyError:
526 if section != DEFAULTSECT:
527 raise NoSectionError(section)
528 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +0000529 if vars:
530 for key, value in vars.items():
531 d[self.optionxform(key)] = value
Fred Drakefce65572002-10-25 18:08:18 +0000532 option = self.optionxform(option)
533 try:
534 value = d[option]
535 except KeyError:
536 raise NoOptionError(option, section)
537
538 if raw:
539 return value
540 else:
541 return self._interpolate(section, option, value, d)
542
Neal Norwitzf680cc42002-12-17 01:56:47 +0000543 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000544 """Return a list of tuples with (name, value) for each option
545 in the section.
546
547 All % interpolations are expanded in the return values, based on the
548 defaults passed into the constructor, unless the optional argument
549 `raw' is true. Additional substitutions may be provided using the
550 `vars' argument, which must be a dictionary whose contents overrides
551 any pre-existing defaults.
552
553 The section DEFAULT is special.
554 """
555 d = self._defaults.copy()
556 try:
557 d.update(self._sections[section])
558 except KeyError:
559 if section != DEFAULTSECT:
560 raise NoSectionError(section)
561 # Update with the entry specific variables
562 if vars:
David Goodger68a1abd2004-10-03 15:40:25 +0000563 for key, value in vars.items():
564 d[self.optionxform(key)] = value
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000565 options = list(d.keys())
Fred Drakedf393bd2002-10-25 20:41:30 +0000566 if "__name__" in options:
567 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000568 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +0000569 return [(option, d[option])
570 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000571 else:
Fred Drake8c4da532003-10-21 16:45:00 +0000572 return [(option, self._interpolate(section, option, d[option], d))
573 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000574
575 def _interpolate(self, section, option, rawval, vars):
576 # do the string interpolation
577 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000578 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000579 while depth: # Loop through this until it's done
580 depth -= 1
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000581 if "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +0000582 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +0000583 try:
584 value = value % vars
Guido van Rossumb940e112007-01-10 16:19:56 +0000585 except KeyError as e:
Fred Drakee2c64912002-12-31 17:23:27 +0000586 raise InterpolationMissingOptionError(
Brett Cannonca477b22007-03-21 22:26:20 +0000587 option, section, rawval, e.args[0])
Fred Drakefce65572002-10-25 18:08:18 +0000588 else:
589 break
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000590 if "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +0000591 raise InterpolationDepthError(option, section, rawval)
592 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000593
Fred Drakebc12b012004-05-18 02:25:51 +0000594 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
595
596 def _interpolation_replace(self, match):
597 s = match.group(1)
598 if s is None:
599 return match.group()
600 else:
601 return "%%(%s)s" % self.optionxform(s)
602
Fred Drake0eebd5c2002-10-25 21:52:00 +0000603
604class SafeConfigParser(ConfigParser):
605
606 def _interpolate(self, section, option, rawval, vars):
607 # do the string interpolation
608 L = []
609 self._interpolate_some(option, L, rawval, section, vars, 1)
610 return ''.join(L)
611
Guido van Rossumd8faa362007-04-27 19:54:29 +0000612 _interpvar_re = re.compile(r"%\(([^)]+)\)s")
613 _badpercent_re = re.compile(r"%[^%]|%$")
Fred Drake0eebd5c2002-10-25 21:52:00 +0000614
615 def _interpolate_some(self, option, accum, rest, section, map, depth):
616 if depth > MAX_INTERPOLATION_DEPTH:
617 raise InterpolationDepthError(option, section, rest)
618 while rest:
619 p = rest.find("%")
620 if p < 0:
621 accum.append(rest)
622 return
623 if p > 0:
624 accum.append(rest[:p])
625 rest = rest[p:]
626 # p is no longer used
627 c = rest[1:2]
628 if c == "%":
629 accum.append("%")
630 rest = rest[2:]
631 elif c == "(":
Guido van Rossumd8faa362007-04-27 19:54:29 +0000632 m = self._interpvar_re.match(rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000633 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +0000634 raise InterpolationSyntaxError(option, section,
635 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +0000636 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +0000637 rest = rest[m.end():]
638 try:
639 v = map[var]
640 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +0000641 raise InterpolationMissingOptionError(
642 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000643 if "%" in v:
644 self._interpolate_some(option, accum, v,
645 section, map, depth + 1)
646 else:
647 accum.append(v)
648 else:
649 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +0000650 option, section,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000651 "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +0000652
653 def set(self, section, option, value):
654 """Set an option. Extend ConfigParser.set: check for string values."""
655 if not isinstance(value, basestring):
656 raise TypeError("option values must be strings")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000657 # check for bad percent signs:
658 # first, replace all "good" interpolations
659 tmp_value = self._interpvar_re.sub('', value)
660 # then, check if there's a lone percent sign left
661 m = self._badpercent_re.search(tmp_value)
662 if m:
663 raise ValueError("invalid interpolation syntax in %r at "
664 "position %d" % (value, m.start()))
David Goodger1cbf2062004-10-03 15:55:09 +0000665 ConfigParser.set(self, section, option, value)