blob: 7ad24d885bfe5cdc17274dbb50b3acc3c253c024 [file] [log] [blame]
Guido van Rossum3d209861997-12-09 16:10:31 +00001"""Configuration file parser.
2
Georg Brandl96a60ae2010-07-28 13:13:46 +00003A configuration file consists of sections, lead by a "[section]" header,
Guido van Rossum3d209861997-12-09 16:10:31 +00004and 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
Georg Brandl96a60ae2010-07-28 13:13:46 +000027 __init__(defaults=None, dict_type=_default_dict,
28 delimiters=('=', ':'), comment_prefixes=('#', ';'),
29 empty_lines_in_values=True, allow_no_value=False):
30 Create the parser. When `defaults' is given, it is initialized into the
31 dictionary or intrinsic defaults. The keys must be strings, the values
32 must be appropriate for %()s string interpolation. Note that `__name__'
33 is always an intrinsic default; its value is the section's name.
34
35 When `dict_type' is given, it will be used to create the dictionary
36 objects for the list of sections, for the options within a section, and
37 for the default values.
38
39 When `delimiters' is given, it will be used as the set of substrings
40 that divide keys from values.
41
42 When `comment_prefixes' is given, it will be used as the set of
43 substrings that prefix comments in a line.
44
45 When `empty_lines_in_values' is False (default: True), each empty line
46 marks the end of an option. Otherwise, internal empty lines of
47 a multiline option are kept as part of the value.
48
49 When `allow_no_value' is True (default: False), options without
50 values are accepted; the value presented for these is None.
Guido van Rossum3d209861997-12-09 16:10:31 +000051
Barry Warsawf09f6a51999-01-26 22:01:37 +000052 sections()
Georg Brandl96a60ae2010-07-28 13:13:46 +000053 Return all the configuration section names, sans DEFAULT.
Guido van Rossum3d209861997-12-09 16:10:31 +000054
Guido van Rossuma5a24b71999-10-04 19:58:22 +000055 has_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000056 Return whether the given section exists.
Guido van Rossuma5a24b71999-10-04 19:58:22 +000057
Eric S. Raymond649685a2000-07-14 14:28:22 +000058 has_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +000059 Return whether the given option exists in the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +000060
Barry Warsawf09f6a51999-01-26 22:01:37 +000061 options(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000062 Return list of configuration options for the named section.
Guido van Rossum3d209861997-12-09 16:10:31 +000063
Georg Brandl8dcaa732010-07-29 12:17:40 +000064 read(filenames, encoding=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000065 Read and parse the list of named configuration files, given by
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000066 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000067 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000068
69 readfp(fp, filename=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000070 Read and parse one configuration file, given as a file object.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000071 The filename defaults to fp.name; it is only used in error
Barry Warsaw25394511999-10-12 16:12:48 +000072 messages (if fp has no `name' attribute, the string `<???>' is used).
Guido van Rossum3d209861997-12-09 16:10:31 +000073
Neal Norwitzf680cc42002-12-17 01:56:47 +000074 get(section, option, raw=False, vars=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000075 Return a string value for the named option. All % interpolations are
Barry Warsawf09f6a51999-01-26 22:01:37 +000076 expanded in the return values, based on the defaults passed into the
77 constructor and the DEFAULT section. Additional substitutions may be
78 provided using the `vars' argument, which must be a dictionary whose
79 contents override any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +000080
Barry Warsawf09f6a51999-01-26 22:01:37 +000081 getint(section, options)
Georg Brandl96a60ae2010-07-28 13:13:46 +000082 Like get(), but convert value to an integer.
Guido van Rossum3d209861997-12-09 16:10:31 +000083
Barry Warsawf09f6a51999-01-26 22:01:37 +000084 getfloat(section, options)
Georg Brandl96a60ae2010-07-28 13:13:46 +000085 Like get(), but convert value to a float.
Guido van Rossum3d209861997-12-09 16:10:31 +000086
Barry Warsawf09f6a51999-01-26 22:01:37 +000087 getboolean(section, options)
Georg Brandl96a60ae2010-07-28 13:13:46 +000088 Like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +000089 insensitively defined as 0, false, no, off for False, and 1, true,
90 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +000091
Neal Norwitzf680cc42002-12-17 01:56:47 +000092 items(section, raw=False, vars=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000093 Return a list of tuples with (name, value) for each option
Fred Drake2ca041f2002-09-27 15:49:56 +000094 in the section.
95
Eric S. Raymond649685a2000-07-14 14:28:22 +000096 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000097 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +000098
99 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000100 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000101
102 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000103 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000104
Georg Brandl96a60ae2010-07-28 13:13:46 +0000105 write(fp, space_around_delimiters=True)
106 Write the configuration state in .ini format. If
107 `space_around_delimiters' is True (the default), delimiters
108 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000109"""
110
Raymond Hettingerff23e8c2009-03-03 01:32:48 +0000111try:
112 from collections import OrderedDict as _default_dict
113except ImportError:
114 # fallback for setup.py which hasn't yet built _collections
115 _default_dict = dict
116
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000117import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000118import sys
Guido van Rossum3d209861997-12-09 16:10:31 +0000119
Fred Drake8d5dd982002-12-30 23:51:45 +0000120__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
121 "InterpolationError", "InterpolationDepthError",
122 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000123 "MissingSectionHeaderError",
124 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000125 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000126
Guido van Rossum3d209861997-12-09 16:10:31 +0000127DEFAULTSECT = "DEFAULT"
128
Fred Drake2a37f9f2000-09-27 22:43:54 +0000129MAX_INTERPOLATION_DEPTH = 10
130
Guido van Rossum3d209861997-12-09 16:10:31 +0000131
Tim Peters88869f92001-01-14 23:36:06 +0000132
Guido van Rossum3d209861997-12-09 16:10:31 +0000133# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000134class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000135 """Base class for ConfigParser exceptions."""
136
Guido van Rossum360e4b82007-05-14 22:51:27 +0000137 def _get_message(self):
138 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000139 BaseException.
140 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000141 return self.__message
142
143 def _set_message(self, value):
144 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000145 BaseException.
146 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000147 self.__message = value
148
149 # BaseException.message has been deprecated since Python 2.6. To prevent
Georg Brandl96a60ae2010-07-28 13:13:46 +0000150 # DeprecationWarning from popping up over this pre-existing attribute, use a
151 # new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000152 message = property(_get_message, _set_message)
153
Guido van Rossum3d209861997-12-09 16:10:31 +0000154 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000155 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000156 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000157
Guido van Rossum3d209861997-12-09 16:10:31 +0000158 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000159 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000160
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000161 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000162
Georg Brandl96a60ae2010-07-28 13:13:46 +0000163
Guido van Rossum3d209861997-12-09 16:10:31 +0000164class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000165 """Raised when no section matches a requested option."""
166
Guido van Rossum3d209861997-12-09 16:10:31 +0000167 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000168 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000169 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000170 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000171
Georg Brandl96a60ae2010-07-28 13:13:46 +0000172
Guido van Rossum3d209861997-12-09 16:10:31 +0000173class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000174 """Raised when a section is multiply-created."""
175
Guido van Rossum3d209861997-12-09 16:10:31 +0000176 def __init__(self, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000177 Error.__init__(self, "Section %r already exists" % section)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000179 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000180
Georg Brandl96a60ae2010-07-28 13:13:46 +0000181
Guido van Rossum3d209861997-12-09 16:10:31 +0000182class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000183 """A requested option was not found."""
184
Guido van Rossum3d209861997-12-09 16:10:31 +0000185 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000186 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000187 (option, section))
188 self.option = option
189 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000190 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000191
Georg Brandl96a60ae2010-07-28 13:13:46 +0000192
Guido van Rossum3d209861997-12-09 16:10:31 +0000193class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000194 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000195
Fred Drakee2c64912002-12-31 17:23:27 +0000196 def __init__(self, option, section, msg):
197 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 self.option = option
199 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000200 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000201
Georg Brandl96a60ae2010-07-28 13:13:46 +0000202
Fred Drakee2c64912002-12-31 17:23:27 +0000203class InterpolationMissingOptionError(InterpolationError):
204 """A string substitution required a setting which was not available."""
205
206 def __init__(self, option, section, rawval, reference):
207 msg = ("Bad value substitution:\n"
208 "\tsection: [%s]\n"
209 "\toption : %s\n"
210 "\tkey : %s\n"
211 "\trawval : %s\n"
212 % (section, option, reference, rawval))
213 InterpolationError.__init__(self, option, section, msg)
214 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000215 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000216
Georg Brandl96a60ae2010-07-28 13:13:46 +0000217
Fred Drakee2c64912002-12-31 17:23:27 +0000218class InterpolationSyntaxError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000219 """Raised when the source text into which substitutions are made
220 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000221
Georg Brandl96a60ae2010-07-28 13:13:46 +0000222
Fred Drakee2c64912002-12-31 17:23:27 +0000223class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000224 """Raised when substitutions are nested too deeply."""
225
Fred Drake2a37f9f2000-09-27 22:43:54 +0000226 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000227 msg = ("Value interpolation too deeply recursive:\n"
228 "\tsection: [%s]\n"
229 "\toption : %s\n"
230 "\trawval : %s\n"
231 % (section, option, rawval))
232 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000233 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000234
Georg Brandl96a60ae2010-07-28 13:13:46 +0000235
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000236class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000237 """Raised when a configuration file does not follow legal syntax."""
238
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000239 def __init__(self, filename):
240 Error.__init__(self, 'File contains parsing errors: %s' % filename)
241 self.filename = filename
242 self.errors = []
Michael Foordbd6c0792010-07-25 23:09:25 +0000243 self.args = (filename, )
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000244
245 def append(self, lineno, line):
246 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000247 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000248
Georg Brandl96a60ae2010-07-28 13:13:46 +0000249
Fred Drake2a37f9f2000-09-27 22:43:54 +0000250class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000251 """Raised when a key-value pair is found before any section header."""
252
Fred Drake2a37f9f2000-09-27 22:43:54 +0000253 def __init__(self, filename, lineno, line):
254 Error.__init__(
255 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000256 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000257 (filename, lineno, line))
258 self.filename = filename
259 self.lineno = lineno
260 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000261 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000262
Georg Brandl96a60ae2010-07-28 13:13:46 +0000263
Fred Drakefce65572002-10-25 18:08:18 +0000264class RawConfigParser:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000265 """ConfigParser that does not do interpolation."""
266
267 # Regular expressions for parsing section headers and options
268 _SECT_TMPL = r"""
269 \[ # [
270 (?P<header>[^]]+) # very permissive!
271 \] # ]
272 """
273 _OPT_TMPL = r"""
274 (?P<option>.*?) # very permissive!
275 \s*(?P<vi>{delim})\s* # any number of space/tab,
276 # followed by any of the
277 # allowed delimiters,
278 # followed by any space/tab
279 (?P<value>.*)$ # everything up to eol
280 """
281 _OPT_NV_TMPL = r"""
282 (?P<option>.*?) # very permissive!
283 \s*(?: # any number of space/tab,
284 (?P<vi>{delim})\s* # optionally followed by
285 # any of the allowed
286 # delimiters, followed by any
287 # space/tab
288 (?P<value>.*))?$ # everything up to eol
289 """
290
291 # Compiled regular expression for matching sections
292 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
293 # Compiled regular expression for matching options with typical separators
294 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
295 # Compiled regular expression for matching options with optional values
296 # delimited using typical separators
297 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
298 # Compiled regular expression for matching leading whitespace in a line
299 NONSPACECRE = re.compile(r"\S")
300 # Select backwards-compatible inline comment character behavior
301 # (; and # are comments at the start of a line, but ; only inline)
302 _COMPATIBLE = object()
303
Fred Drake03c44a32010-02-19 06:08:41 +0000304 def __init__(self, defaults=None, dict_type=_default_dict,
Georg Brandl96a60ae2010-07-28 13:13:46 +0000305 delimiters=('=', ':'), comment_prefixes=_COMPATIBLE,
306 empty_lines_in_values=True, allow_no_value=False):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307 self._dict = dict_type
308 self._sections = self._dict()
309 self._defaults = self._dict()
David Goodger68a1abd2004-10-03 15:40:25 +0000310 if defaults:
311 for key, value in defaults.items():
312 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000313 self._delimiters = tuple(delimiters)
314 if delimiters == ('=', ':'):
315 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
316 else:
317 delim = "|".join(re.escape(d) for d in delimiters)
318 if allow_no_value:
319 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=delim),
320 re.VERBOSE)
321 else:
322 self._optcre = re.compile(self._OPT_TMPL.format(delim=delim),
323 re.VERBOSE)
324 if comment_prefixes is self._COMPATIBLE:
325 self._startonly_comment_prefixes = ('#',)
326 self._comment_prefixes = (';',)
327 else:
328 self._startonly_comment_prefixes = ()
329 self._comment_prefixes = tuple(comment_prefixes or ())
330 self._empty_lines_in_values = empty_lines_in_values
Guido van Rossum3d209861997-12-09 16:10:31 +0000331
332 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000333 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000334
335 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000336 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000337 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000338 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000339
340 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000341 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000342
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000343 Raise DuplicateSectionError if a section by the specified name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000344 already exists. Raise ValueError if name is DEFAULT or any of it's
345 case-insensitive variants.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000346 """
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000347 if section.lower() == "default":
348 raise ValueError('Invalid section name: %s' % section)
349
Fred Drakefce65572002-10-25 18:08:18 +0000350 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000351 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000352 self._sections[section] = self._dict()
Guido van Rossum3d209861997-12-09 16:10:31 +0000353
354 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000355 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000356
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000357 The DEFAULT section is not acknowledged.
358 """
Fred Drakefce65572002-10-25 18:08:18 +0000359 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000360
361 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000362 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000363 try:
Fred Drakefce65572002-10-25 18:08:18 +0000364 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000365 except KeyError:
366 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000367 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000368 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000369 del opts['__name__']
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000370 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000371
Georg Brandl8dcaa732010-07-29 12:17:40 +0000372 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000373 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000374
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000375 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000376 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000377 configuration file locations (e.g. current directory, user's
378 home directory, systemwide directory), and all existing
379 configuration files in the list will be read. A single
380 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000381
382 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000383 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000384 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000385 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000386 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000387 for filename in filenames:
388 try:
Georg Brandl8dcaa732010-07-29 12:17:40 +0000389 fp = open(filename, encoding=encoding)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000390 except IOError:
391 continue
Fred Drakefce65572002-10-25 18:08:18 +0000392 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000393 fp.close()
Fred Drake82903142004-05-18 04:24:02 +0000394 read_ok.append(filename)
395 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000396
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000397 def readfp(self, fp, filename=None):
398 """Like read() but the argument must be a file-like object.
399
400 The `fp' argument must have a `readline' method. Optional
401 second argument is the `filename', which if not given, is
402 taken from fp.name. If fp has no `name' attribute, `<???>' is
403 used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000404 """
405 if filename is None:
406 try:
407 filename = fp.name
408 except AttributeError:
409 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000410 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000411
Fred Drakefce65572002-10-25 18:08:18 +0000412 def get(self, section, option):
413 opt = self.optionxform(option)
414 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000415 if section != DEFAULTSECT:
416 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000417 if opt in self._defaults:
418 return self._defaults[opt]
419 else:
420 raise NoOptionError(option, section)
421 elif opt in self._sections[section]:
422 return self._sections[section][opt]
423 elif opt in self._defaults:
424 return self._defaults[opt]
425 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000427
Fred Drakefce65572002-10-25 18:08:18 +0000428 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000429 try:
Fred Drakefce65572002-10-25 18:08:18 +0000430 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000431 except KeyError:
432 if section != DEFAULTSECT:
433 raise NoSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000434 d2 = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000435 d = self._defaults.copy()
436 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000437 if "__name__" in d:
438 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000439 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000440
Fred Drakefce65572002-10-25 18:08:18 +0000441 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000442 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000443
444 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000445 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000446
447 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000448 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000449
Fred Drakec2ff9052002-09-27 15:33:11 +0000450 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
451 '0': False, 'no': False, 'false': False, 'off': False}
452
Guido van Rossum3d209861997-12-09 16:10:31 +0000453 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000454 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000455 if v.lower() not in self._boolean_states:
Collin Winterce36ad82007-08-30 01:19:48 +0000456 raise ValueError('Not a boolean: %s' % v)
Fred Drakec2ff9052002-09-27 15:33:11 +0000457 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000458
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000459 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000460 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000461
Eric S. Raymond417c4892000-07-10 18:11:00 +0000462 def has_option(self, section, option):
463 """Check for the existence of a given option in a given section."""
Georg Brandl96a60ae2010-07-28 13:13:46 +0000464
Fred Drakec2ff9052002-09-27 15:33:11 +0000465 if not section or section == DEFAULTSECT:
466 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000467 return option in self._defaults
468 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000469 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000470 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000471 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000472 return (option in self._sections[section]
473 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000474
Fred Drake03c44a32010-02-19 06:08:41 +0000475 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000476 """Set an option."""
Georg Brandl96a60ae2010-07-28 13:13:46 +0000477
Fred Drakec2ff9052002-09-27 15:33:11 +0000478 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000479 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000480 else:
481 try:
Fred Drakefce65572002-10-25 18:08:18 +0000482 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000483 except KeyError:
484 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000485 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000486
Georg Brandl96a60ae2010-07-28 13:13:46 +0000487 def write(self, fp, space_around_delimiters=True):
488 """Write an .ini-format representation of the configuration state.
489
490 If `space_around_delimiters' is True (the default), delimiters
491 between keys and values are surrounded by spaces.
492 """
493 if space_around_delimiters:
494 d = " {} ".format(self._delimiters[0])
495 else:
496 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000497 if self._defaults:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000498 self._write_section(fp, DEFAULTSECT, self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000499 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000500 self._write_section(fp, section,
501 self._sections[section].items(), d)
502
503 def _write_section(self, fp, section_name, section_items, delimiter):
504 """Write a single section to the specified `fp'."""
505 fp.write("[{}]\n".format(section_name))
506 for key, value in section_items:
507 if key == "__name__":
508 continue
509 if value is not None:
510 value = delimiter + str(value).replace('\n', '\n\t')
511 else:
512 value = ""
513 fp.write("{}{}\n".format(key, value))
514 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000515
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000516 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000517 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000518 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000519 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000520 else:
521 try:
Fred Drakefce65572002-10-25 18:08:18 +0000522 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000523 except KeyError:
524 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000525 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000526 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000527 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000528 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000529 return existed
530
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000531 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000532 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000533 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000534 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000535 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000536 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000537
Fred Drakefce65572002-10-25 18:08:18 +0000538 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000539 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000540
Georg Brandl96a60ae2010-07-28 13:13:46 +0000541 Each section in a configuration file contains a header, indicated by a
542 name in square brackets (`[]'), plus key/value options, indicated by
543 `name' and `value' delimited with a specific substring (`=' or `:' by
544 default).
545
546 Values can span multiple lines, as long as they are indented deeper than
547 the first line of the value. Depending on the parser's mode, blank lines
548 may be treated as parts of multiline values or ignored.
549
550 Configuration files may include comments, prefixed by specific
551 characters (`#' and `;' by default). Comments may appear on their own in
552 an otherwise empty line or may be entered in lines holding values or
553 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000554 """
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000555 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000556 optname = None
557 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000558 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000559 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000560 for lineno, line in enumerate(fp, start=1):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000561 # strip full line comments
Georg Brandl96a60ae2010-07-28 13:13:46 +0000562 comment_start = None
563 for prefix in self._startonly_comment_prefixes:
564 if line.strip().startswith(prefix):
565 comment_start = 0
566 break
567 # strip inline comments
568 for prefix in self._comment_prefixes:
569 index = line.find(prefix)
570 if index == 0 or (index > 0 and line[index-1].isspace()):
571 comment_start = index
572 break
573 value = line[:comment_start].strip()
574 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +0000575 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000576 # add empty line to the value, but only if there was no
577 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +0000578 if (comment_start is None and
579 cursect is not None and
580 optname and
581 cursect[optname] is not None):
582 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +0000583 else:
584 # empty line marks end of value
585 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000586 continue
587 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +0000588 first_nonspace = self.NONSPACECRE.search(line)
589 cur_indent_level = first_nonspace.start() if first_nonspace else 0
590 if (cursect is not None and optname and
591 cur_indent_level > indent_level):
592 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000593 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000594 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000595 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000596 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +0000597 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000598 if mo:
599 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000600 if sectname in self._sections:
601 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000602 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000603 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000604 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000605 cursect = self._dict()
606 cursect['__name__'] = sectname
Fred Drakefce65572002-10-25 18:08:18 +0000607 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000608 # So sections can't start with a continuation line
609 optname = None
610 # no section header in the file?
611 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000612 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000613 # an option line?
614 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000615 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000616 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000617 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +0000618 if not optname:
619 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000620 optname = self.optionxform(optname.rstrip())
Fred Drake03c44a32010-02-19 06:08:41 +0000621 # This check is fine because the OPTCRE cannot
622 # match if it would set optval to None
623 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +0000624 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000625 # allow empty values
626 if optval == '""':
627 optval = ''
628 cursect[optname] = [optval]
629 else:
630 # valueless option handling
631 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000632 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000633 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000634 # exception but keep going. the exception will be
635 # raised at the end of the file and will contain a
636 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +0000637 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000638 # if any parsing errors occurred, raise an exception
639 if e:
640 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +0000641 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +0000642
Georg Brandl96a60ae2010-07-28 13:13:46 +0000643 def _join_multiline_values(self):
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000644 all_sections = [self._defaults]
645 all_sections.extend(self._sections.values())
646 for options in all_sections:
647 for name, val in options.items():
648 if isinstance(val, list):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000649 options[name] = '\n'.join(val).rstrip()
Fred Drakefce65572002-10-25 18:08:18 +0000650
Georg Brandl96a60ae2010-07-28 13:13:46 +0000651 def _handle_error(self, exc, fpname, lineno, line):
652 if not exc:
653 exc = ParsingError(fpname)
654 exc.append(lineno, repr(line))
655 return exc
656
657
Fred Drakefce65572002-10-25 18:08:18 +0000658class ConfigParser(RawConfigParser):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000659 """ConfigParser implementing interpolation."""
Fred Drakefce65572002-10-25 18:08:18 +0000660
Neal Norwitzf680cc42002-12-17 01:56:47 +0000661 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000662 """Get an option value for a given section.
663
664 All % interpolations are expanded in the return values, based on the
665 defaults passed into the constructor, unless the optional argument
666 `raw' is true. Additional substitutions may be provided using the
667 `vars' argument, which must be a dictionary whose contents overrides
668 any pre-existing defaults.
669
670 The section DEFAULT is special.
671 """
672 d = self._defaults.copy()
673 try:
674 d.update(self._sections[section])
675 except KeyError:
676 if section != DEFAULTSECT:
677 raise NoSectionError(section)
678 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +0000679 if vars:
680 for key, value in vars.items():
681 d[self.optionxform(key)] = value
Fred Drakefce65572002-10-25 18:08:18 +0000682 option = self.optionxform(option)
683 try:
684 value = d[option]
685 except KeyError:
686 raise NoOptionError(option, section)
687
Fred Drake03c44a32010-02-19 06:08:41 +0000688 if raw or value is None:
Fred Drakefce65572002-10-25 18:08:18 +0000689 return value
690 else:
691 return self._interpolate(section, option, value, d)
692
Neal Norwitzf680cc42002-12-17 01:56:47 +0000693 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000694 """Return a list of tuples with (name, value) for each option
695 in the section.
696
697 All % interpolations are expanded in the return values, based on the
698 defaults passed into the constructor, unless the optional argument
699 `raw' is true. Additional substitutions may be provided using the
700 `vars' argument, which must be a dictionary whose contents overrides
701 any pre-existing defaults.
702
703 The section DEFAULT is special.
704 """
705 d = self._defaults.copy()
706 try:
707 d.update(self._sections[section])
708 except KeyError:
709 if section != DEFAULTSECT:
710 raise NoSectionError(section)
711 # Update with the entry specific variables
712 if vars:
David Goodger68a1abd2004-10-03 15:40:25 +0000713 for key, value in vars.items():
714 d[self.optionxform(key)] = value
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000715 options = list(d.keys())
Fred Drakedf393bd2002-10-25 20:41:30 +0000716 if "__name__" in options:
717 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000718 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +0000719 return [(option, d[option])
720 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000721 else:
Fred Drake8c4da532003-10-21 16:45:00 +0000722 return [(option, self._interpolate(section, option, d[option], d))
723 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000724
725 def _interpolate(self, section, option, rawval, vars):
726 # do the string interpolation
727 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000728 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000729 while depth: # Loop through this until it's done
730 depth -= 1
Fred Drake03c44a32010-02-19 06:08:41 +0000731 if value and "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +0000732 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +0000733 try:
734 value = value % vars
Guido van Rossumb940e112007-01-10 16:19:56 +0000735 except KeyError as e:
Fred Drakee2c64912002-12-31 17:23:27 +0000736 raise InterpolationMissingOptionError(
Brett Cannonca477b22007-03-21 22:26:20 +0000737 option, section, rawval, e.args[0])
Fred Drakefce65572002-10-25 18:08:18 +0000738 else:
739 break
Fred Drake03c44a32010-02-19 06:08:41 +0000740 if value and "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +0000741 raise InterpolationDepthError(option, section, rawval)
742 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000743
Fred Drakebc12b012004-05-18 02:25:51 +0000744 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
745
746 def _interpolation_replace(self, match):
747 s = match.group(1)
748 if s is None:
749 return match.group()
750 else:
751 return "%%(%s)s" % self.optionxform(s)
752
Fred Drake0eebd5c2002-10-25 21:52:00 +0000753
754class SafeConfigParser(ConfigParser):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000755 """ConfigParser implementing sane interpolation."""
Fred Drake0eebd5c2002-10-25 21:52:00 +0000756
757 def _interpolate(self, section, option, rawval, vars):
758 # do the string interpolation
759 L = []
760 self._interpolate_some(option, L, rawval, section, vars, 1)
761 return ''.join(L)
762
Guido van Rossumd8faa362007-04-27 19:54:29 +0000763 _interpvar_re = re.compile(r"%\(([^)]+)\)s")
Fred Drake0eebd5c2002-10-25 21:52:00 +0000764
765 def _interpolate_some(self, option, accum, rest, section, map, depth):
766 if depth > MAX_INTERPOLATION_DEPTH:
767 raise InterpolationDepthError(option, section, rest)
768 while rest:
769 p = rest.find("%")
770 if p < 0:
771 accum.append(rest)
772 return
773 if p > 0:
774 accum.append(rest[:p])
775 rest = rest[p:]
776 # p is no longer used
777 c = rest[1:2]
778 if c == "%":
779 accum.append("%")
780 rest = rest[2:]
781 elif c == "(":
Guido van Rossumd8faa362007-04-27 19:54:29 +0000782 m = self._interpvar_re.match(rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000783 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +0000784 raise InterpolationSyntaxError(option, section,
785 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +0000786 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +0000787 rest = rest[m.end():]
788 try:
789 v = map[var]
790 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +0000791 raise InterpolationMissingOptionError(
792 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000793 if "%" in v:
794 self._interpolate_some(option, accum, v,
795 section, map, depth + 1)
796 else:
797 accum.append(v)
798 else:
799 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +0000800 option, section,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000801 "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +0000802
Fred Drake03c44a32010-02-19 06:08:41 +0000803 def set(self, section, option, value=None):
David Goodger1cbf2062004-10-03 15:55:09 +0000804 """Set an option. Extend ConfigParser.set: check for string values."""
Fred Drake03c44a32010-02-19 06:08:41 +0000805 # The only legal non-string value if we allow valueless
806 # options is None, so we need to check if the value is a
807 # string if:
808 # - we do not allow valueless options, or
809 # - we allow valueless options but the value is not None
810 if self._optcre is self.OPTCRE or value:
811 if not isinstance(value, str):
812 raise TypeError("option values must be strings")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000813 # check for bad percent signs:
814 # first, replace all "good" interpolations
Georg Brandl68998bf2009-04-27 16:43:36 +0000815 tmp_value = value.replace('%%', '')
816 tmp_value = self._interpvar_re.sub('', tmp_value)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000817 # then, check if there's a lone percent sign left
Georg Brandl1f9fa312009-04-27 16:42:58 +0000818 percent_index = tmp_value.find('%')
819 if percent_index != -1:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000820 raise ValueError("invalid interpolation syntax in %r at "
Georg Brandl1f9fa312009-04-27 16:42:58 +0000821 "position %d" % (value, percent_index))
David Goodger1cbf2062004-10-03 15:55:09 +0000822 ConfigParser.set(self, section, option, value)