blob: f9bb32cda815121ebdced0a490cbcfb7732fdbeb [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
Fred Drakecc645b92010-09-04 04:35:34 +000027 __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
28 delimiters=('=', ':'), comment_prefixes=_COMPATIBLE,
29 strict=False, empty_lines_in_values=True):
Georg Brandl96a60ae2010-07-28 13:13:46 +000030 Create the parser. When `defaults' is given, it is initialized into the
31 dictionary or intrinsic defaults. The keys must be strings, the values
Łukasz Langa5c863392010-11-21 13:41:35 +000032 must be appropriate for %()s string interpolation.
Georg Brandl96a60ae2010-07-28 13:13:46 +000033
34 When `dict_type' is given, it will be used to create the dictionary
35 objects for the list of sections, for the options within a section, and
36 for the default values.
37
38 When `delimiters' is given, it will be used as the set of substrings
39 that divide keys from values.
40
41 When `comment_prefixes' is given, it will be used as the set of
42 substrings that prefix comments in a line.
43
Fred Drakea4923622010-08-09 12:52:45 +000044 When `strict` is True, the parser won't allow for any section or option
45 duplicates while reading from a single source (file, string or
46 dictionary). Default is False.
47
Georg Brandl96a60ae2010-07-28 13:13:46 +000048 When `empty_lines_in_values' is False (default: True), each empty line
49 marks the end of an option. Otherwise, internal empty lines of
50 a multiline option are kept as part of the value.
51
52 When `allow_no_value' is True (default: False), options without
53 values are accepted; the value presented for these is None.
Guido van Rossum3d209861997-12-09 16:10:31 +000054
Barry Warsawf09f6a51999-01-26 22:01:37 +000055 sections()
Georg Brandl96a60ae2010-07-28 13:13:46 +000056 Return all the configuration section names, sans DEFAULT.
Guido van Rossum3d209861997-12-09 16:10:31 +000057
Guido van Rossuma5a24b71999-10-04 19:58:22 +000058 has_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000059 Return whether the given section exists.
Guido van Rossuma5a24b71999-10-04 19:58:22 +000060
Eric S. Raymond649685a2000-07-14 14:28:22 +000061 has_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +000062 Return whether the given option exists in the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +000063
Barry Warsawf09f6a51999-01-26 22:01:37 +000064 options(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000065 Return list of configuration options for the named section.
Guido van Rossum3d209861997-12-09 16:10:31 +000066
Georg Brandl8dcaa732010-07-29 12:17:40 +000067 read(filenames, encoding=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000068 Read and parse the list of named configuration files, given by
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000069 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000070 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000071
Fred Drakea4923622010-08-09 12:52:45 +000072 read_file(f, filename=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000073 Read and parse one configuration file, given as a file object.
Fred Drakea4923622010-08-09 12:52:45 +000074 The filename defaults to f.name; it is only used in error
75 messages (if f has no `name' attribute, the string `<???>' is used).
76
77 read_string(string)
78 Read configuration from a given string.
79
80 read_dict(dictionary)
81 Read configuration from a dictionary. Keys are section names,
82 values are dictionaries with keys and values that should be present
83 in the section. If the used dictionary type preserves order, sections
Fred Drakecc645b92010-09-04 04:35:34 +000084 and their keys will be added in order. Values are automatically
85 converted to strings.
Guido van Rossum3d209861997-12-09 16:10:31 +000086
Łukasz Langa26d513c2010-11-10 18:57:39 +000087 get(section, option, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000088 Return a string value for the named option. All % interpolations are
Barry Warsawf09f6a51999-01-26 22:01:37 +000089 expanded in the return values, based on the defaults passed into the
90 constructor and the DEFAULT section. Additional substitutions may be
91 provided using the `vars' argument, which must be a dictionary whose
Fred Drakecc645b92010-09-04 04:35:34 +000092 contents override any pre-existing defaults. If `option' is a key in
93 `vars', the value from `vars' is used.
Guido van Rossum3d209861997-12-09 16:10:31 +000094
Łukasz Langa26d513c2010-11-10 18:57:39 +000095 getint(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000096 Like get(), but convert value to an integer.
Guido van Rossum3d209861997-12-09 16:10:31 +000097
Łukasz Langa26d513c2010-11-10 18:57:39 +000098 getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000099 Like get(), but convert value to a float.
Guido van Rossum3d209861997-12-09 16:10:31 +0000100
Łukasz Langa26d513c2010-11-10 18:57:39 +0000101 getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000102 Like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +0000103 insensitively defined as 0, false, no, off for False, and 1, true,
104 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000105
Neal Norwitzf680cc42002-12-17 01:56:47 +0000106 items(section, raw=False, vars=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000107 Return a list of tuples with (name, value) for each option
Fred Drake2ca041f2002-09-27 15:49:56 +0000108 in the section.
109
Eric S. Raymond649685a2000-07-14 14:28:22 +0000110 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000111 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000112
113 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000114 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000115
116 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000117 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000118
Georg Brandl96a60ae2010-07-28 13:13:46 +0000119 write(fp, space_around_delimiters=True)
120 Write the configuration state in .ini format. If
121 `space_around_delimiters' is True (the default), delimiters
122 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000123"""
124
Łukasz Langa26d513c2010-11-10 18:57:39 +0000125from collections import MutableMapping, OrderedDict as _default_dict
126import functools
Fred Drakea4923622010-08-09 12:52:45 +0000127import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000128import itertools
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000129import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000130import sys
Fred Drakea4923622010-08-09 12:52:45 +0000131import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000132
Fred Drakea4923622010-08-09 12:52:45 +0000133__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
134 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Fred Drake8d5dd982002-12-30 23:51:45 +0000135 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000136 "MissingSectionHeaderError",
137 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000138 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000139
Guido van Rossum3d209861997-12-09 16:10:31 +0000140DEFAULTSECT = "DEFAULT"
141
Fred Drake2a37f9f2000-09-27 22:43:54 +0000142MAX_INTERPOLATION_DEPTH = 10
143
Guido van Rossum3d209861997-12-09 16:10:31 +0000144
Tim Peters88869f92001-01-14 23:36:06 +0000145
Guido van Rossum3d209861997-12-09 16:10:31 +0000146# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000147class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000148 """Base class for ConfigParser exceptions."""
149
Guido van Rossum360e4b82007-05-14 22:51:27 +0000150 def _get_message(self):
151 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000152 BaseException.
153 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000154 return self.__message
155
156 def _set_message(self, value):
157 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000158 BaseException.
159 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000160 self.__message = value
161
162 # BaseException.message has been deprecated since Python 2.6. To prevent
Fred Drakea4923622010-08-09 12:52:45 +0000163 # DeprecationWarning from popping up over this pre-existing attribute, use
164 # a new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000165 message = property(_get_message, _set_message)
166
Guido van Rossum3d209861997-12-09 16:10:31 +0000167 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000168 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000169 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000170
Guido van Rossum3d209861997-12-09 16:10:31 +0000171 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000172 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000173
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000174 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000175
Georg Brandl96a60ae2010-07-28 13:13:46 +0000176
Guido van Rossum3d209861997-12-09 16:10:31 +0000177class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000178 """Raised when no section matches a requested option."""
179
Guido van Rossum3d209861997-12-09 16:10:31 +0000180 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000181 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000183 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000184
Georg Brandl96a60ae2010-07-28 13:13:46 +0000185
Guido van Rossum3d209861997-12-09 16:10:31 +0000186class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000187 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000188
Fred Drakea4923622010-08-09 12:52:45 +0000189 Possible repetitions that raise this exception are: multiple creation
190 using the API or in strict parsers when a section is found more than once
191 in a single input file, string or dictionary.
192 """
193
194 def __init__(self, section, source=None, lineno=None):
195 msg = [repr(section), " already exists"]
196 if source is not None:
197 message = ["While reading from ", source]
198 if lineno is not None:
199 message.append(" [line {0:2d}]".format(lineno))
200 message.append(": section ")
201 message.extend(msg)
202 msg = message
203 else:
204 msg.insert(0, "Section ")
205 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000207 self.source = source
208 self.lineno = lineno
209 self.args = (section, source, lineno)
210
211
212class DuplicateOptionError(Error):
213 """Raised by strict parsers when an option is repeated in an input source.
214
215 Current implementation raises this exception only when an option is found
216 more than once in a single file, string or dictionary.
217 """
218
219 def __init__(self, section, option, source=None, lineno=None):
220 msg = [repr(option), " in section ", repr(section),
221 " already exists"]
222 if source is not None:
223 message = ["While reading from ", source]
224 if lineno is not None:
225 message.append(" [line {0:2d}]".format(lineno))
226 message.append(": option ")
227 message.extend(msg)
228 msg = message
229 else:
230 msg.insert(0, "Option ")
231 Error.__init__(self, "".join(msg))
232 self.section = section
233 self.option = option
234 self.source = source
235 self.lineno = lineno
236 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000237
Georg Brandl96a60ae2010-07-28 13:13:46 +0000238
Guido van Rossum3d209861997-12-09 16:10:31 +0000239class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000240 """A requested option was not found."""
241
Guido van Rossum3d209861997-12-09 16:10:31 +0000242 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000243 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000244 (option, section))
245 self.option = option
246 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000247 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000248
Georg Brandl96a60ae2010-07-28 13:13:46 +0000249
Guido van Rossum3d209861997-12-09 16:10:31 +0000250class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000251 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000252
Fred Drakee2c64912002-12-31 17:23:27 +0000253 def __init__(self, option, section, msg):
254 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000255 self.option = option
256 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000257 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000258
Georg Brandl96a60ae2010-07-28 13:13:46 +0000259
Fred Drakee2c64912002-12-31 17:23:27 +0000260class InterpolationMissingOptionError(InterpolationError):
261 """A string substitution required a setting which was not available."""
262
263 def __init__(self, option, section, rawval, reference):
264 msg = ("Bad value substitution:\n"
265 "\tsection: [%s]\n"
266 "\toption : %s\n"
267 "\tkey : %s\n"
268 "\trawval : %s\n"
269 % (section, option, reference, rawval))
270 InterpolationError.__init__(self, option, section, msg)
271 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000272 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000273
Georg Brandl96a60ae2010-07-28 13:13:46 +0000274
Fred Drakee2c64912002-12-31 17:23:27 +0000275class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000276 """Raised when the source text contains invalid syntax.
277
278 Current implementation raises this exception only for SafeConfigParser
279 instances when the source text into which substitutions are made
280 does not conform to the required syntax.
281 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000282
Georg Brandl96a60ae2010-07-28 13:13:46 +0000283
Fred Drakee2c64912002-12-31 17:23:27 +0000284class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000285 """Raised when substitutions are nested too deeply."""
286
Fred Drake2a37f9f2000-09-27 22:43:54 +0000287 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000288 msg = ("Value interpolation too deeply recursive:\n"
289 "\tsection: [%s]\n"
290 "\toption : %s\n"
291 "\trawval : %s\n"
292 % (section, option, rawval))
293 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000294 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000295
Georg Brandl96a60ae2010-07-28 13:13:46 +0000296
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000297class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000298 """Raised when a configuration file does not follow legal syntax."""
299
Fred Drakea4923622010-08-09 12:52:45 +0000300 def __init__(self, source=None, filename=None):
301 # Exactly one of `source'/`filename' arguments has to be given.
302 # `filename' kept for compatibility.
303 if filename and source:
304 raise ValueError("Cannot specify both `filename' and `source'. "
305 "Use `source'.")
306 elif not filename and not source:
307 raise ValueError("Required argument `source' not given.")
308 elif filename:
309 source = filename
310 Error.__init__(self, 'Source contains parsing errors: %s' % source)
311 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000312 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000313 self.args = (source, )
314
315 @property
316 def filename(self):
317 """Deprecated, use `source'."""
318 warnings.warn(
319 "This 'filename' attribute will be removed in future versions. "
320 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000321 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000322 )
323 return self.source
324
325 @filename.setter
326 def filename(self, value):
327 """Deprecated, user `source'."""
328 warnings.warn(
329 "The 'filename' attribute will be removed in future versions. "
330 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000331 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000332 )
333 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000334
335 def append(self, lineno, line):
336 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000337 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000338
Georg Brandl96a60ae2010-07-28 13:13:46 +0000339
Fred Drake2a37f9f2000-09-27 22:43:54 +0000340class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000341 """Raised when a key-value pair is found before any section header."""
342
Fred Drake2a37f9f2000-09-27 22:43:54 +0000343 def __init__(self, filename, lineno, line):
344 Error.__init__(
345 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000346 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000347 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000348 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000349 self.lineno = lineno
350 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000351 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000352
Georg Brandl96a60ae2010-07-28 13:13:46 +0000353
Fred Drakecc645b92010-09-04 04:35:34 +0000354# Used in parsers to denote selecting a backwards-compatible inline comment
355# character behavior (; and # are comments at the start of a line, but ; only
356# inline)
357_COMPATIBLE = object()
358
359# Used in parser getters to indicate the default behaviour when a specific
360# option is not found it to raise an exception. Created to enable `None' as
361# a valid fallback value.
362_UNSET = object()
363
364
Łukasz Langa26d513c2010-11-10 18:57:39 +0000365class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000366 """ConfigParser that does not do interpolation."""
367
368 # Regular expressions for parsing section headers and options
369 _SECT_TMPL = r"""
370 \[ # [
371 (?P<header>[^]]+) # very permissive!
372 \] # ]
373 """
374 _OPT_TMPL = r"""
375 (?P<option>.*?) # very permissive!
376 \s*(?P<vi>{delim})\s* # any number of space/tab,
377 # followed by any of the
378 # allowed delimiters,
379 # followed by any space/tab
380 (?P<value>.*)$ # everything up to eol
381 """
382 _OPT_NV_TMPL = r"""
383 (?P<option>.*?) # very permissive!
384 \s*(?: # any number of space/tab,
385 (?P<vi>{delim})\s* # optionally followed by
386 # any of the allowed
387 # delimiters, followed by any
388 # space/tab
389 (?P<value>.*))?$ # everything up to eol
390 """
391
392 # Compiled regular expression for matching sections
393 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
394 # Compiled regular expression for matching options with typical separators
395 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
396 # Compiled regular expression for matching options with optional values
397 # delimited using typical separators
398 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
399 # Compiled regular expression for matching leading whitespace in a line
400 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000401 # Possible boolean values in the configuration.
402 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
403 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000404
Fred Drake03c44a32010-02-19 06:08:41 +0000405 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000406 allow_no_value=False, *, delimiters=('=', ':'),
407 comment_prefixes=_COMPATIBLE, strict=False,
Łukasz Langac264c092010-11-20 16:15:37 +0000408 empty_lines_in_values=True,
409 default_section=DEFAULTSECT):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000410 self._dict = dict_type
411 self._sections = self._dict()
412 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000413 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000414 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000415 if defaults:
416 for key, value in defaults.items():
417 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000418 self._delimiters = tuple(delimiters)
419 if delimiters == ('=', ':'):
420 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
421 else:
Fred Drakea4923622010-08-09 12:52:45 +0000422 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000423 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000424 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000425 re.VERBOSE)
426 else:
Fred Drakea4923622010-08-09 12:52:45 +0000427 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000428 re.VERBOSE)
Fred Drakecc645b92010-09-04 04:35:34 +0000429 if comment_prefixes is _COMPATIBLE:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000430 self._startonly_comment_prefixes = ('#',)
431 self._comment_prefixes = (';',)
432 else:
433 self._startonly_comment_prefixes = ()
434 self._comment_prefixes = tuple(comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000435 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000436 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000437 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langac264c092010-11-20 16:15:37 +0000438 self._default_section=default_section
Guido van Rossum3d209861997-12-09 16:10:31 +0000439
440 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000441 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000442
443 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000444 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000445 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000446 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000447
448 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000449 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000450
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000451 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000452 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000453 """
Łukasz Langac264c092010-11-20 16:15:37 +0000454 if section == self._default_section:
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000455 raise ValueError('Invalid section name: %s' % section)
456
Fred Drakefce65572002-10-25 18:08:18 +0000457 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000458 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000459 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000460 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000461
462 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000463 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000464
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000465 The DEFAULT section is not acknowledged.
466 """
Fred Drakefce65572002-10-25 18:08:18 +0000467 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000468
469 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000470 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000471 try:
Fred Drakefce65572002-10-25 18:08:18 +0000472 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000473 except KeyError:
474 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000475 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000476 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000477
Georg Brandl8dcaa732010-07-29 12:17:40 +0000478 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000479 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000480
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000481 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000482 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000483 configuration file locations (e.g. current directory, user's
484 home directory, systemwide directory), and all existing
485 configuration files in the list will be read. A single
486 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000487
488 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000489 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000490 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000491 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000492 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000493 for filename in filenames:
494 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000495 with open(filename, encoding=encoding) as fp:
496 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000497 except IOError:
498 continue
Fred Drake82903142004-05-18 04:24:02 +0000499 read_ok.append(filename)
500 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000501
Fred Drakea4923622010-08-09 12:52:45 +0000502 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000503 """Like read() but the argument must be a file-like object.
504
Fred Drakea4923622010-08-09 12:52:45 +0000505 The `f' argument must have a `readline' method. Optional second
506 argument is the `source' specifying the name of the file being read. If
507 not given, it is taken from f.name. If `f' has no `name' attribute,
508 `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000509 """
Fred Drakea4923622010-08-09 12:52:45 +0000510 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000511 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000512 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000513 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000514 source = '<???>'
515 self._read(f, source)
516
517 def read_string(self, string, source='<string>'):
518 """Read configuration from a given string."""
519 sfile = io.StringIO(string)
520 self.read_file(sfile, source)
521
522 def read_dict(self, dictionary, source='<dict>'):
523 """Read configuration from a dictionary.
524
525 Keys are section names, values are dictionaries with keys and values
526 that should be present in the section. If the used dictionary type
527 preserves order, sections and their keys will be added in order.
528
529 Optional second argument is the `source' specifying the name of the
530 dictionary being read.
531 """
532 elements_added = set()
533 for section, keys in dictionary.items():
534 try:
535 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000536 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000537 if self._strict and section in elements_added:
538 raise
539 elements_added.add(section)
540 for key, value in keys.items():
541 key = self.optionxform(key)
Fred Drakecc645b92010-09-04 04:35:34 +0000542 if value is not None:
543 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000544 if self._strict and (section, key) in elements_added:
545 raise DuplicateOptionError(section, key, source)
546 elements_added.add((section, key))
547 self.set(section, key, value)
548
549 def readfp(self, fp, filename=None):
550 """Deprecated, use read_file instead."""
551 warnings.warn(
552 "This method will be removed in future versions. "
553 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000554 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000555 )
556 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000557
Łukasz Langa26d513c2010-11-10 18:57:39 +0000558 def get(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000559 """Get an option value for a given section.
560
561 If `vars' is provided, it must be a dictionary. The option is looked up
562 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000563 If the key is not found and `fallback' is provided, it is used as
564 a fallback value. `None' can be provided as a `fallback' value.
565
566 Arguments `vars' and `fallback' are keyword only.
Fred Drakecc645b92010-09-04 04:35:34 +0000567 """
568 try:
569 d = self._unify_values(section, vars)
570 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000571 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000572 raise
Fred Drakefce65572002-10-25 18:08:18 +0000573 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000574 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000575 option = self.optionxform(option)
576 try:
577 return d[option]
578 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000579 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000580 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000581 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000582 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000583
Fred Drakefce65572002-10-25 18:08:18 +0000584 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000585 try:
Fred Drakefce65572002-10-25 18:08:18 +0000586 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000587 except KeyError:
Łukasz Langac264c092010-11-20 16:15:37 +0000588 if section != self._default_section:
Fred Drake2ca041f2002-09-27 15:49:56 +0000589 raise NoSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000590 d2 = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000591 d = self._defaults.copy()
592 d.update(d2)
593 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000594
Łukasz Langa26d513c2010-11-10 18:57:39 +0000595 def _get(self, section, conv, option, **kwargs):
596 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000597
Łukasz Langa26d513c2010-11-10 18:57:39 +0000598 def getint(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000599 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000600 return self._get(section, int, option, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000601 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000602 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000603 raise
604 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000605 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000606
Łukasz Langa26d513c2010-11-10 18:57:39 +0000607 def getfloat(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000608 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000609 return self._get(section, float, option, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000610 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000611 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000612 raise
613 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000614 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000615
Łukasz Langa26d513c2010-11-10 18:57:39 +0000616 def getboolean(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000617 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000618 return self._get(section, self._convert_to_boolean, option,
619 vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000620 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000621 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000622 raise
623 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000624 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000625
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000626 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000627 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000628
Eric S. Raymond417c4892000-07-10 18:11:00 +0000629 def has_option(self, section, option):
630 """Check for the existence of a given option in a given section."""
Łukasz Langac264c092010-11-20 16:15:37 +0000631 if not section or section == self._default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000632 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000633 return option in self._defaults
634 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000635 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000636 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000637 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000638 return (option in self._sections[section]
639 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000640
Fred Drake03c44a32010-02-19 06:08:41 +0000641 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000642 """Set an option."""
Łukasz Langac264c092010-11-20 16:15:37 +0000643 if not section or section == self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000644 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000645 else:
646 try:
Fred Drakefce65572002-10-25 18:08:18 +0000647 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000648 except KeyError:
649 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000650 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000651
Georg Brandl96a60ae2010-07-28 13:13:46 +0000652 def write(self, fp, space_around_delimiters=True):
653 """Write an .ini-format representation of the configuration state.
654
655 If `space_around_delimiters' is True (the default), delimiters
656 between keys and values are surrounded by spaces.
657 """
658 if space_around_delimiters:
659 d = " {} ".format(self._delimiters[0])
660 else:
661 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000662 if self._defaults:
Łukasz Langac264c092010-11-20 16:15:37 +0000663 self._write_section(fp, self._default_section,
664 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000665 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000666 self._write_section(fp, section,
667 self._sections[section].items(), d)
668
669 def _write_section(self, fp, section_name, section_items, delimiter):
670 """Write a single section to the specified `fp'."""
671 fp.write("[{}]\n".format(section_name))
672 for key, value in section_items:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000673 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000674 value = delimiter + str(value).replace('\n', '\n\t')
675 else:
676 value = ""
677 fp.write("{}{}\n".format(key, value))
678 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000679
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000680 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000681 """Remove an option."""
Łukasz Langac264c092010-11-20 16:15:37 +0000682 if not section or section == self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000683 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000684 else:
685 try:
Fred Drakefce65572002-10-25 18:08:18 +0000686 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000687 except KeyError:
688 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000689 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000690 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000691 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000692 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000693 return existed
694
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000695 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000696 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000697 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000698 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000699 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000700 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000701 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000702
Łukasz Langa26d513c2010-11-10 18:57:39 +0000703 def __getitem__(self, key):
Łukasz Langac264c092010-11-20 16:15:37 +0000704 if key != self._default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000705 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000706 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000707
708 def __setitem__(self, key, value):
709 # To conform with the mapping protocol, overwrites existing values in
710 # the section.
711
712 # XXX this is not atomic if read_dict fails at any point. Then again,
713 # no update method in configparser is atomic in this implementation.
714 self.remove_section(key)
715 self.read_dict({key: value})
716
717 def __delitem__(self, key):
Łukasz Langac264c092010-11-20 16:15:37 +0000718 if key == self._default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000719 raise ValueError("Cannot remove the default section.")
720 if not self.has_section(key):
721 raise KeyError(key)
722 self.remove_section(key)
723
724 def __contains__(self, key):
Łukasz Langac264c092010-11-20 16:15:37 +0000725 return key == self._default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000726
727 def __len__(self):
728 return len(self._sections) + 1 # the default section
729
730 def __iter__(self):
731 # XXX does it break when underlying container state changed?
Łukasz Langac264c092010-11-20 16:15:37 +0000732 return itertools.chain((self._default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000733
Fred Drakefce65572002-10-25 18:08:18 +0000734 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000735 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000736
Fred Drakea4923622010-08-09 12:52:45 +0000737 Each section in a configuration file contains a header, indicated by
738 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000739 `name' and `value' delimited with a specific substring (`=' or `:' by
740 default).
741
Fred Drakea4923622010-08-09 12:52:45 +0000742 Values can span multiple lines, as long as they are indented deeper
743 than the first line of the value. Depending on the parser's mode, blank
744 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000745
746 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000747 characters (`#' and `;' by default). Comments may appear on their own
748 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000749 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000750 """
Fred Drakea4923622010-08-09 12:52:45 +0000751 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000752 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +0000753 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000754 optname = None
755 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000756 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000757 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000758 for lineno, line in enumerate(fp, start=1):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000759 # strip full line comments
Georg Brandl96a60ae2010-07-28 13:13:46 +0000760 comment_start = None
761 for prefix in self._startonly_comment_prefixes:
762 if line.strip().startswith(prefix):
763 comment_start = 0
764 break
765 # strip inline comments
766 for prefix in self._comment_prefixes:
767 index = line.find(prefix)
768 if index == 0 or (index > 0 and line[index-1].isspace()):
769 comment_start = index
770 break
771 value = line[:comment_start].strip()
772 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +0000773 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000774 # add empty line to the value, but only if there was no
775 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +0000776 if (comment_start is None and
777 cursect is not None and
778 optname and
779 cursect[optname] is not None):
780 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +0000781 else:
782 # empty line marks end of value
783 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000784 continue
785 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +0000786 first_nonspace = self.NONSPACECRE.search(line)
787 cur_indent_level = first_nonspace.start() if first_nonspace else 0
788 if (cursect is not None and optname and
789 cur_indent_level > indent_level):
790 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000791 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000792 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000793 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000794 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +0000795 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000796 if mo:
797 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000798 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +0000799 if self._strict and sectname in elements_added:
800 raise DuplicateSectionError(sectname, fpname,
801 lineno)
Fred Drakefce65572002-10-25 18:08:18 +0000802 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +0000803 elements_added.add(sectname)
Łukasz Langac264c092010-11-20 16:15:37 +0000804 elif sectname == self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000805 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000806 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000807 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000808 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +0000809 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +0000810 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000811 # So sections can't start with a continuation line
812 optname = None
813 # no section header in the file?
814 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000815 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000816 # an option line?
817 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000818 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000819 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000820 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +0000821 if not optname:
822 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000823 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +0000824 if (self._strict and
825 (sectname, optname) in elements_added):
826 raise DuplicateOptionError(sectname, optname,
827 fpname, lineno)
828 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +0000829 # This check is fine because the OPTCRE cannot
830 # match if it would set optval to None
831 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +0000832 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000833 # allow empty values
834 if optval == '""':
835 optval = ''
836 cursect[optname] = [optval]
837 else:
838 # valueless option handling
839 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000840 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000841 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000842 # exception but keep going. the exception will be
843 # raised at the end of the file and will contain a
844 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +0000845 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000846 # if any parsing errors occurred, raise an exception
847 if e:
848 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +0000849 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +0000850
Georg Brandl96a60ae2010-07-28 13:13:46 +0000851 def _join_multiline_values(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000852 all_sections = itertools.chain((self._defaults,),
853 self._sections.values())
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000854 for options in all_sections:
855 for name, val in options.items():
856 if isinstance(val, list):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000857 options[name] = '\n'.join(val).rstrip()
Fred Drakefce65572002-10-25 18:08:18 +0000858
Georg Brandl96a60ae2010-07-28 13:13:46 +0000859 def _handle_error(self, exc, fpname, lineno, line):
860 if not exc:
861 exc = ParsingError(fpname)
862 exc.append(lineno, repr(line))
863 return exc
864
Fred Drakecc645b92010-09-04 04:35:34 +0000865 def _unify_values(self, section, vars):
866 """Create a copy of the DEFAULTSECT with values from a specific
867 `section' and the `vars' dictionary. If provided, values in `vars'
868 take precendence.
Fred Drakefce65572002-10-25 18:08:18 +0000869 """
870 d = self._defaults.copy()
871 try:
872 d.update(self._sections[section])
873 except KeyError:
Łukasz Langac264c092010-11-20 16:15:37 +0000874 if section != self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000875 raise NoSectionError(section)
876 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +0000877 if vars:
878 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +0000879 if value is not None:
880 value = str(value)
David Goodger68a1abd2004-10-03 15:40:25 +0000881 d[self.optionxform(key)] = value
Fred Drakecc645b92010-09-04 04:35:34 +0000882 return d
883
884 def _convert_to_boolean(self, value):
885 """Return a boolean value translating from other types if necessary.
886 """
887 if value.lower() not in self.BOOLEAN_STATES:
888 raise ValueError('Not a boolean: %s' % value)
889 return self.BOOLEAN_STATES[value.lower()]
890
Łukasz Langa26d513c2010-11-10 18:57:39 +0000891 def _validate_value_type(self, value):
892 """Raises a TypeError for non-string values.
893
894 The only legal non-string value if we allow valueless
895 options is None, so we need to check if the value is a
896 string if:
897 - we do not allow valueless options, or
898 - we allow valueless options but the value is not None
899
900 For compatibility reasons this method is not used in classic set()
901 for RawConfigParsers and ConfigParsers. It is invoked in every
902 case for mapping protocol access and in SafeConfigParser.set().
903 """
904 if not self._allow_no_value or value:
905 if not isinstance(value, str):
906 raise TypeError("option values must be strings")
907
908
Fred Drakecc645b92010-09-04 04:35:34 +0000909
910class ConfigParser(RawConfigParser):
911 """ConfigParser implementing interpolation."""
912
Łukasz Langa26d513c2010-11-10 18:57:39 +0000913 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000914 """Get an option value for a given section.
915
916 If `vars' is provided, it must be a dictionary. The option is looked up
917 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000918 If the key is not found and `fallback' is provided, it is used as
919 a fallback value. `None' can be provided as a `fallback' value.
Fred Drakecc645b92010-09-04 04:35:34 +0000920
921 All % interpolations are expanded in the return values, unless the
922 optional argument `raw' is true. Values for interpolation keys are
923 looked up in the same manner as the option.
924
Łukasz Langa26d513c2010-11-10 18:57:39 +0000925 Arguments `raw', `vars', and `fallback' are keyword only.
926
Fred Drakecc645b92010-09-04 04:35:34 +0000927 The section DEFAULT is special.
928 """
929 try:
930 d = self._unify_values(section, vars)
931 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000932 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000933 raise
934 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000935 return fallback
Fred Drakefce65572002-10-25 18:08:18 +0000936 option = self.optionxform(option)
937 try:
938 value = d[option]
939 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000940 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000941 raise NoOptionError(option, section)
942 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000943 return fallback
Fred Drakefce65572002-10-25 18:08:18 +0000944
Fred Drake03c44a32010-02-19 06:08:41 +0000945 if raw or value is None:
Fred Drakefce65572002-10-25 18:08:18 +0000946 return value
947 else:
948 return self._interpolate(section, option, value, d)
949
Łukasz Langa26d513c2010-11-10 18:57:39 +0000950 def getint(self, section, option, *, raw=False, vars=None,
951 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000952 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000953 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000954 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000955 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000956 raise
957 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000958 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000959
Łukasz Langa26d513c2010-11-10 18:57:39 +0000960 def getfloat(self, section, option, *, raw=False, vars=None,
961 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000962 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000963 return self._get(section, float, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000964 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000965 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000966 raise
967 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000968 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000969
Łukasz Langa26d513c2010-11-10 18:57:39 +0000970 def getboolean(self, section, option, *, raw=False, vars=None,
971 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000972 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000973 return self._get(section, self._convert_to_boolean, option,
974 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000975 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000976 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000977 raise
978 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000979 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000980
Neal Norwitzf680cc42002-12-17 01:56:47 +0000981 def items(self, section, raw=False, vars=None):
Fred Drakea4923622010-08-09 12:52:45 +0000982 """Return a list of (name, value) tuples for each option in a section.
Fred Drakefce65572002-10-25 18:08:18 +0000983
984 All % interpolations are expanded in the return values, based on the
985 defaults passed into the constructor, unless the optional argument
986 `raw' is true. Additional substitutions may be provided using the
987 `vars' argument, which must be a dictionary whose contents overrides
988 any pre-existing defaults.
989
990 The section DEFAULT is special.
991 """
992 d = self._defaults.copy()
993 try:
994 d.update(self._sections[section])
995 except KeyError:
Łukasz Langac264c092010-11-20 16:15:37 +0000996 if section != self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000997 raise NoSectionError(section)
998 # Update with the entry specific variables
999 if vars:
David Goodger68a1abd2004-10-03 15:40:25 +00001000 for key, value in vars.items():
1001 d[self.optionxform(key)] = value
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001002 options = list(d.keys())
Fred Drakefce65572002-10-25 18:08:18 +00001003 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +00001004 return [(option, d[option])
1005 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +00001006 else:
Fred Drake8c4da532003-10-21 16:45:00 +00001007 return [(option, self._interpolate(section, option, d[option], d))
1008 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +00001009
1010 def _interpolate(self, section, option, rawval, vars):
1011 # do the string interpolation
1012 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +00001013 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +00001014 while depth: # Loop through this until it's done
1015 depth -= 1
Fred Drake03c44a32010-02-19 06:08:41 +00001016 if value and "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +00001017 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +00001018 try:
1019 value = value % vars
Guido van Rossumb940e112007-01-10 16:19:56 +00001020 except KeyError as e:
Fred Drakee2c64912002-12-31 17:23:27 +00001021 raise InterpolationMissingOptionError(
Brett Cannonca477b22007-03-21 22:26:20 +00001022 option, section, rawval, e.args[0])
Fred Drakefce65572002-10-25 18:08:18 +00001023 else:
1024 break
Fred Drake03c44a32010-02-19 06:08:41 +00001025 if value and "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +00001026 raise InterpolationDepthError(option, section, rawval)
1027 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +00001028
Fred Drakebc12b012004-05-18 02:25:51 +00001029 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
1030
1031 def _interpolation_replace(self, match):
1032 s = match.group(1)
1033 if s is None:
1034 return match.group()
1035 else:
1036 return "%%(%s)s" % self.optionxform(s)
1037
Fred Drake0eebd5c2002-10-25 21:52:00 +00001038
1039class SafeConfigParser(ConfigParser):
Georg Brandl96a60ae2010-07-28 13:13:46 +00001040 """ConfigParser implementing sane interpolation."""
Fred Drake0eebd5c2002-10-25 21:52:00 +00001041
1042 def _interpolate(self, section, option, rawval, vars):
1043 # do the string interpolation
1044 L = []
1045 self._interpolate_some(option, L, rawval, section, vars, 1)
1046 return ''.join(L)
1047
Guido van Rossumd8faa362007-04-27 19:54:29 +00001048 _interpvar_re = re.compile(r"%\(([^)]+)\)s")
Fred Drake0eebd5c2002-10-25 21:52:00 +00001049
1050 def _interpolate_some(self, option, accum, rest, section, map, depth):
1051 if depth > MAX_INTERPOLATION_DEPTH:
1052 raise InterpolationDepthError(option, section, rest)
1053 while rest:
1054 p = rest.find("%")
1055 if p < 0:
1056 accum.append(rest)
1057 return
1058 if p > 0:
1059 accum.append(rest[:p])
1060 rest = rest[p:]
1061 # p is no longer used
1062 c = rest[1:2]
1063 if c == "%":
1064 accum.append("%")
1065 rest = rest[2:]
1066 elif c == "(":
Guido van Rossumd8faa362007-04-27 19:54:29 +00001067 m = self._interpvar_re.match(rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +00001068 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +00001069 raise InterpolationSyntaxError(option, section,
1070 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +00001071 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +00001072 rest = rest[m.end():]
1073 try:
1074 v = map[var]
1075 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +00001076 raise InterpolationMissingOptionError(
1077 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +00001078 if "%" in v:
1079 self._interpolate_some(option, accum, v,
1080 section, map, depth + 1)
1081 else:
1082 accum.append(v)
1083 else:
1084 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +00001085 option, section,
Fred Drakea4923622010-08-09 12:52:45 +00001086 "'%%' must be followed by '%%' or '(', "
1087 "found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +00001088
Fred Drake03c44a32010-02-19 06:08:41 +00001089 def set(self, section, option, value=None):
David Goodger1cbf2062004-10-03 15:55:09 +00001090 """Set an option. Extend ConfigParser.set: check for string values."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001091 self._validate_value_type(value)
Fred Drakea4923622010-08-09 12:52:45 +00001092 # check for bad percent signs
1093 if value:
1094 tmp_value = value.replace('%%', '') # escaped percent signs
1095 tmp_value = self._interpvar_re.sub('', tmp_value) # valid syntax
1096 if '%' in tmp_value:
1097 raise ValueError("invalid interpolation syntax in %r at "
1098 "position %d" % (value, tmp_value.find('%')))
David Goodger1cbf2062004-10-03 15:55:09 +00001099 ConfigParser.set(self, section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001100
1101
1102class SectionProxy(MutableMapping):
1103 """A proxy for a single section from a parser."""
1104
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001105 def __init__(self, parser, name):
1106 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001107 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001108 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001109 self.getint = functools.partial(self._parser.getint,
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001110 self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001111 self.getfloat = functools.partial(self._parser.getfloat,
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001112 self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001113 self.getboolean = functools.partial(self._parser.getboolean,
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001114 self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001115
1116 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001117 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001118
1119 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001120 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001121 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001122 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001123
1124 def __setitem__(self, key, value):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001125 self._parser._validate_value_type(value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001126 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001127
1128 def __delitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001129 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001130 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001131 return self._parser.remove_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001132
1133 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001134 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001135
1136 def __len__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001137 # XXX weak performance
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001138 return len(self._parser.options(self._name))
Łukasz Langa26d513c2010-11-10 18:57:39 +00001139
1140 def __iter__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001141 # XXX weak performance
1142 # XXX does not break when underlying container state changed
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001143 return self._parser.options(self._name).__iter__()
1144
1145 @property
1146 def parser(self):
1147 # The parser object of the proxy is read-only.
1148 return self._parser
1149
1150 @property
1151 def name(self):
1152 # The name of the section on a proxy is read-only.
1153 return self._name