blob: 03f98a6fe2ce39afe1cbe31d6c47c650b6343fa2 [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
Fred Drakea4923622010-08-09 12:52:45 +000032 must be appropriate for %()s string interpolation. Note that `__name__'
Georg Brandl96a60ae2010-07-28 13:13:46 +000033 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
Fred Drakea4923622010-08-09 12:52:45 +000045 When `strict` is True, the parser won't allow for any section or option
46 duplicates while reading from a single source (file, string or
47 dictionary). Default is False.
48
Georg Brandl96a60ae2010-07-28 13:13:46 +000049 When `empty_lines_in_values' is False (default: True), each empty line
50 marks the end of an option. Otherwise, internal empty lines of
51 a multiline option are kept as part of the value.
52
53 When `allow_no_value' is True (default: False), options without
54 values are accepted; the value presented for these is None.
Guido van Rossum3d209861997-12-09 16:10:31 +000055
Barry Warsawf09f6a51999-01-26 22:01:37 +000056 sections()
Georg Brandl96a60ae2010-07-28 13:13:46 +000057 Return all the configuration section names, sans DEFAULT.
Guido van Rossum3d209861997-12-09 16:10:31 +000058
Guido van Rossuma5a24b71999-10-04 19:58:22 +000059 has_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000060 Return whether the given section exists.
Guido van Rossuma5a24b71999-10-04 19:58:22 +000061
Eric S. Raymond649685a2000-07-14 14:28:22 +000062 has_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +000063 Return whether the given option exists in the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +000064
Barry Warsawf09f6a51999-01-26 22:01:37 +000065 options(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000066 Return list of configuration options for the named section.
Guido van Rossum3d209861997-12-09 16:10:31 +000067
Georg Brandl8dcaa732010-07-29 12:17:40 +000068 read(filenames, encoding=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000069 Read and parse the list of named configuration files, given by
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000070 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000071 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000072
Fred Drakea4923622010-08-09 12:52:45 +000073 read_file(f, filename=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000074 Read and parse one configuration file, given as a file object.
Fred Drakea4923622010-08-09 12:52:45 +000075 The filename defaults to f.name; it is only used in error
76 messages (if f has no `name' attribute, the string `<???>' is used).
77
78 read_string(string)
79 Read configuration from a given string.
80
81 read_dict(dictionary)
82 Read configuration from a dictionary. Keys are section names,
83 values are dictionaries with keys and values that should be present
84 in the section. If the used dictionary type preserves order, sections
Fred Drakecc645b92010-09-04 04:35:34 +000085 and their keys will be added in order. Values are automatically
86 converted to strings.
Guido van Rossum3d209861997-12-09 16:10:31 +000087
Łukasz Langa26d513c2010-11-10 18:57:39 +000088 get(section, option, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000089 Return a string value for the named option. All % interpolations are
Barry Warsawf09f6a51999-01-26 22:01:37 +000090 expanded in the return values, based on the defaults passed into the
91 constructor and the DEFAULT section. Additional substitutions may be
92 provided using the `vars' argument, which must be a dictionary whose
Fred Drakecc645b92010-09-04 04:35:34 +000093 contents override any pre-existing defaults. If `option' is a key in
94 `vars', the value from `vars' is used.
Guido van Rossum3d209861997-12-09 16:10:31 +000095
Łukasz Langa26d513c2010-11-10 18:57:39 +000096 getint(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000097 Like get(), but convert value to an integer.
Guido van Rossum3d209861997-12-09 16:10:31 +000098
Łukasz Langa26d513c2010-11-10 18:57:39 +000099 getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000100 Like get(), but convert value to a float.
Guido van Rossum3d209861997-12-09 16:10:31 +0000101
Łukasz Langa26d513c2010-11-10 18:57:39 +0000102 getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000103 Like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +0000104 insensitively defined as 0, false, no, off for False, and 1, true,
105 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000106
Neal Norwitzf680cc42002-12-17 01:56:47 +0000107 items(section, raw=False, vars=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000108 Return a list of tuples with (name, value) for each option
Fred Drake2ca041f2002-09-27 15:49:56 +0000109 in the section.
110
Eric S. Raymond649685a2000-07-14 14:28:22 +0000111 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000112 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000113
114 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000115 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000116
117 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000118 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000119
Georg Brandl96a60ae2010-07-28 13:13:46 +0000120 write(fp, space_around_delimiters=True)
121 Write the configuration state in .ini format. If
122 `space_around_delimiters' is True (the default), delimiters
123 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000124"""
125
Łukasz Langa26d513c2010-11-10 18:57:39 +0000126from collections import MutableMapping, OrderedDict as _default_dict
127import functools
Fred Drakea4923622010-08-09 12:52:45 +0000128import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000129import itertools
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000130import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000131import sys
Fred Drakea4923622010-08-09 12:52:45 +0000132import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000133
Fred Drakea4923622010-08-09 12:52:45 +0000134__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
135 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Fred Drake8d5dd982002-12-30 23:51:45 +0000136 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000137 "MissingSectionHeaderError",
138 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000139 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000140
Guido van Rossum3d209861997-12-09 16:10:31 +0000141DEFAULTSECT = "DEFAULT"
142
Fred Drake2a37f9f2000-09-27 22:43:54 +0000143MAX_INTERPOLATION_DEPTH = 10
144
Guido van Rossum3d209861997-12-09 16:10:31 +0000145
Tim Peters88869f92001-01-14 23:36:06 +0000146
Guido van Rossum3d209861997-12-09 16:10:31 +0000147# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000148class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000149 """Base class for ConfigParser exceptions."""
150
Guido van Rossum360e4b82007-05-14 22:51:27 +0000151 def _get_message(self):
152 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000153 BaseException.
154 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000155 return self.__message
156
157 def _set_message(self, value):
158 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000159 BaseException.
160 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000161 self.__message = value
162
163 # BaseException.message has been deprecated since Python 2.6. To prevent
Fred Drakea4923622010-08-09 12:52:45 +0000164 # DeprecationWarning from popping up over this pre-existing attribute, use
165 # a new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000166 message = property(_get_message, _set_message)
167
Guido van Rossum3d209861997-12-09 16:10:31 +0000168 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000169 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000170 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000171
Guido van Rossum3d209861997-12-09 16:10:31 +0000172 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000173 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000174
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000175 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000176
Georg Brandl96a60ae2010-07-28 13:13:46 +0000177
Guido van Rossum3d209861997-12-09 16:10:31 +0000178class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000179 """Raised when no section matches a requested option."""
180
Guido van Rossum3d209861997-12-09 16:10:31 +0000181 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000182 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000183 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000184 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000185
Georg Brandl96a60ae2010-07-28 13:13:46 +0000186
Guido van Rossum3d209861997-12-09 16:10:31 +0000187class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000188 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000189
Fred Drakea4923622010-08-09 12:52:45 +0000190 Possible repetitions that raise this exception are: multiple creation
191 using the API or in strict parsers when a section is found more than once
192 in a single input file, string or dictionary.
193 """
194
195 def __init__(self, section, source=None, lineno=None):
196 msg = [repr(section), " already exists"]
197 if source is not None:
198 message = ["While reading from ", source]
199 if lineno is not None:
200 message.append(" [line {0:2d}]".format(lineno))
201 message.append(": section ")
202 message.extend(msg)
203 msg = message
204 else:
205 msg.insert(0, "Section ")
206 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000207 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000208 self.source = source
209 self.lineno = lineno
210 self.args = (section, source, lineno)
211
212
213class DuplicateOptionError(Error):
214 """Raised by strict parsers when an option is repeated in an input source.
215
216 Current implementation raises this exception only when an option is found
217 more than once in a single file, string or dictionary.
218 """
219
220 def __init__(self, section, option, source=None, lineno=None):
221 msg = [repr(option), " in section ", repr(section),
222 " already exists"]
223 if source is not None:
224 message = ["While reading from ", source]
225 if lineno is not None:
226 message.append(" [line {0:2d}]".format(lineno))
227 message.append(": option ")
228 message.extend(msg)
229 msg = message
230 else:
231 msg.insert(0, "Option ")
232 Error.__init__(self, "".join(msg))
233 self.section = section
234 self.option = option
235 self.source = source
236 self.lineno = lineno
237 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000238
Georg Brandl96a60ae2010-07-28 13:13:46 +0000239
Guido van Rossum3d209861997-12-09 16:10:31 +0000240class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000241 """A requested option was not found."""
242
Guido van Rossum3d209861997-12-09 16:10:31 +0000243 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000244 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 (option, section))
246 self.option = option
247 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000248 self.args = (option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000249
Georg Brandl96a60ae2010-07-28 13:13:46 +0000250
Guido van Rossum3d209861997-12-09 16:10:31 +0000251class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000252 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000253
Fred Drakee2c64912002-12-31 17:23:27 +0000254 def __init__(self, option, section, msg):
255 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 self.option = option
257 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000258 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000259
Georg Brandl96a60ae2010-07-28 13:13:46 +0000260
Fred Drakee2c64912002-12-31 17:23:27 +0000261class InterpolationMissingOptionError(InterpolationError):
262 """A string substitution required a setting which was not available."""
263
264 def __init__(self, option, section, rawval, reference):
265 msg = ("Bad value substitution:\n"
266 "\tsection: [%s]\n"
267 "\toption : %s\n"
268 "\tkey : %s\n"
269 "\trawval : %s\n"
270 % (section, option, reference, rawval))
271 InterpolationError.__init__(self, option, section, msg)
272 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000273 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000274
Georg Brandl96a60ae2010-07-28 13:13:46 +0000275
Fred Drakee2c64912002-12-31 17:23:27 +0000276class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000277 """Raised when the source text contains invalid syntax.
278
279 Current implementation raises this exception only for SafeConfigParser
280 instances when the source text into which substitutions are made
281 does not conform to the required syntax.
282 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000283
Georg Brandl96a60ae2010-07-28 13:13:46 +0000284
Fred Drakee2c64912002-12-31 17:23:27 +0000285class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000286 """Raised when substitutions are nested too deeply."""
287
Fred Drake2a37f9f2000-09-27 22:43:54 +0000288 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000289 msg = ("Value interpolation too deeply recursive:\n"
290 "\tsection: [%s]\n"
291 "\toption : %s\n"
292 "\trawval : %s\n"
293 % (section, option, rawval))
294 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000295 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000296
Georg Brandl96a60ae2010-07-28 13:13:46 +0000297
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000298class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000299 """Raised when a configuration file does not follow legal syntax."""
300
Fred Drakea4923622010-08-09 12:52:45 +0000301 def __init__(self, source=None, filename=None):
302 # Exactly one of `source'/`filename' arguments has to be given.
303 # `filename' kept for compatibility.
304 if filename and source:
305 raise ValueError("Cannot specify both `filename' and `source'. "
306 "Use `source'.")
307 elif not filename and not source:
308 raise ValueError("Required argument `source' not given.")
309 elif filename:
310 source = filename
311 Error.__init__(self, 'Source contains parsing errors: %s' % source)
312 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000313 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000314 self.args = (source, )
315
316 @property
317 def filename(self):
318 """Deprecated, use `source'."""
319 warnings.warn(
320 "This 'filename' attribute will be removed in future versions. "
321 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000322 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000323 )
324 return self.source
325
326 @filename.setter
327 def filename(self, value):
328 """Deprecated, user `source'."""
329 warnings.warn(
330 "The 'filename' attribute will be removed in future versions. "
331 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000332 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000333 )
334 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000335
336 def append(self, lineno, line):
337 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000338 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000339
Georg Brandl96a60ae2010-07-28 13:13:46 +0000340
Fred Drake2a37f9f2000-09-27 22:43:54 +0000341class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000342 """Raised when a key-value pair is found before any section header."""
343
Fred Drake2a37f9f2000-09-27 22:43:54 +0000344 def __init__(self, filename, lineno, line):
345 Error.__init__(
346 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000347 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000348 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000349 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000350 self.lineno = lineno
351 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000352 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000353
Georg Brandl96a60ae2010-07-28 13:13:46 +0000354
Fred Drakecc645b92010-09-04 04:35:34 +0000355# Used in parsers to denote selecting a backwards-compatible inline comment
356# character behavior (; and # are comments at the start of a line, but ; only
357# inline)
358_COMPATIBLE = object()
359
360# Used in parser getters to indicate the default behaviour when a specific
361# option is not found it to raise an exception. Created to enable `None' as
362# a valid fallback value.
363_UNSET = object()
364
365
Łukasz Langa26d513c2010-11-10 18:57:39 +0000366class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000367 """ConfigParser that does not do interpolation."""
368
369 # Regular expressions for parsing section headers and options
370 _SECT_TMPL = r"""
371 \[ # [
372 (?P<header>[^]]+) # very permissive!
373 \] # ]
374 """
375 _OPT_TMPL = r"""
376 (?P<option>.*?) # very permissive!
377 \s*(?P<vi>{delim})\s* # any number of space/tab,
378 # followed by any of the
379 # allowed delimiters,
380 # followed by any space/tab
381 (?P<value>.*)$ # everything up to eol
382 """
383 _OPT_NV_TMPL = r"""
384 (?P<option>.*?) # very permissive!
385 \s*(?: # any number of space/tab,
386 (?P<vi>{delim})\s* # optionally followed by
387 # any of the allowed
388 # delimiters, followed by any
389 # space/tab
390 (?P<value>.*))?$ # everything up to eol
391 """
392
393 # Compiled regular expression for matching sections
394 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
395 # Compiled regular expression for matching options with typical separators
396 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
397 # Compiled regular expression for matching options with optional values
398 # delimited using typical separators
399 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
400 # Compiled regular expression for matching leading whitespace in a line
401 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000402 # Possible boolean values in the configuration.
403 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
404 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000405
Fred Drake03c44a32010-02-19 06:08:41 +0000406 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000407 allow_no_value=False, *, delimiters=('=', ':'),
408 comment_prefixes=_COMPATIBLE, strict=False,
Łukasz Langac264c092010-11-20 16:15:37 +0000409 empty_lines_in_values=True,
410 default_section=DEFAULTSECT):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000411 self._dict = dict_type
412 self._sections = self._dict()
413 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000414 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000415 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000416 if defaults:
417 for key, value in defaults.items():
418 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000419 self._delimiters = tuple(delimiters)
420 if delimiters == ('=', ':'):
421 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
422 else:
Fred Drakea4923622010-08-09 12:52:45 +0000423 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000424 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000425 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000426 re.VERBOSE)
427 else:
Fred Drakea4923622010-08-09 12:52:45 +0000428 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000429 re.VERBOSE)
Fred Drakecc645b92010-09-04 04:35:34 +0000430 if comment_prefixes is _COMPATIBLE:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000431 self._startonly_comment_prefixes = ('#',)
432 self._comment_prefixes = (';',)
433 else:
434 self._startonly_comment_prefixes = ()
435 self._comment_prefixes = tuple(comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000436 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000437 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000438 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langac264c092010-11-20 16:15:37 +0000439 self._default_section=default_section
Guido van Rossum3d209861997-12-09 16:10:31 +0000440
441 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000442 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000443
444 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000445 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000446 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000447 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000448
449 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000451
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000452 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000453 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000454 """
Łukasz Langac264c092010-11-20 16:15:37 +0000455 if section == self._default_section:
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000456 raise ValueError('Invalid section name: %s' % section)
457
Fred Drakefce65572002-10-25 18:08:18 +0000458 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000459 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000461 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000462
463 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000464 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000465
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000466 The DEFAULT section is not acknowledged.
467 """
Fred Drakefce65572002-10-25 18:08:18 +0000468 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000469
470 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000471 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000472 try:
Fred Drakefce65572002-10-25 18:08:18 +0000473 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000474 except KeyError:
475 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000476 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000477 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000478 del opts['__name__']
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000479 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000480
Georg Brandl8dcaa732010-07-29 12:17:40 +0000481 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000482 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000483
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000484 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000485 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000486 configuration file locations (e.g. current directory, user's
487 home directory, systemwide directory), and all existing
488 configuration files in the list will be read. A single
489 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000490
491 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000492 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000493 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000494 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000495 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000496 for filename in filenames:
497 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000498 with open(filename, encoding=encoding) as fp:
499 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000500 except IOError:
501 continue
Fred Drake82903142004-05-18 04:24:02 +0000502 read_ok.append(filename)
503 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000504
Fred Drakea4923622010-08-09 12:52:45 +0000505 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000506 """Like read() but the argument must be a file-like object.
507
Fred Drakea4923622010-08-09 12:52:45 +0000508 The `f' argument must have a `readline' method. Optional second
509 argument is the `source' specifying the name of the file being read. If
510 not given, it is taken from f.name. If `f' has no `name' attribute,
511 `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000512 """
Fred Drakea4923622010-08-09 12:52:45 +0000513 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000514 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000515 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000516 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000517 source = '<???>'
518 self._read(f, source)
519
520 def read_string(self, string, source='<string>'):
521 """Read configuration from a given string."""
522 sfile = io.StringIO(string)
523 self.read_file(sfile, source)
524
525 def read_dict(self, dictionary, source='<dict>'):
526 """Read configuration from a dictionary.
527
528 Keys are section names, values are dictionaries with keys and values
529 that should be present in the section. If the used dictionary type
530 preserves order, sections and their keys will be added in order.
531
532 Optional second argument is the `source' specifying the name of the
533 dictionary being read.
534 """
535 elements_added = set()
536 for section, keys in dictionary.items():
537 try:
538 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000539 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000540 if self._strict and section in elements_added:
541 raise
542 elements_added.add(section)
543 for key, value in keys.items():
544 key = self.optionxform(key)
Fred Drakecc645b92010-09-04 04:35:34 +0000545 if value is not None:
546 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000547 if self._strict and (section, key) in elements_added:
548 raise DuplicateOptionError(section, key, source)
549 elements_added.add((section, key))
550 self.set(section, key, value)
551
552 def readfp(self, fp, filename=None):
553 """Deprecated, use read_file instead."""
554 warnings.warn(
555 "This method will be removed in future versions. "
556 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000557 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000558 )
559 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000560
Łukasz Langa26d513c2010-11-10 18:57:39 +0000561 def get(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000562 """Get an option value for a given section.
563
564 If `vars' is provided, it must be a dictionary. The option is looked up
565 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000566 If the key is not found and `fallback' is provided, it is used as
567 a fallback value. `None' can be provided as a `fallback' value.
568
569 Arguments `vars' and `fallback' are keyword only.
Fred Drakecc645b92010-09-04 04:35:34 +0000570 """
571 try:
572 d = self._unify_values(section, vars)
573 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000574 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000575 raise
Fred Drakefce65572002-10-25 18:08:18 +0000576 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000577 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000578 option = self.optionxform(option)
579 try:
580 return d[option]
581 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000582 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000583 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000584 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000585 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000586
Fred Drakefce65572002-10-25 18:08:18 +0000587 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000588 try:
Fred Drakefce65572002-10-25 18:08:18 +0000589 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000590 except KeyError:
Łukasz Langac264c092010-11-20 16:15:37 +0000591 if section != self._default_section:
Fred Drake2ca041f2002-09-27 15:49:56 +0000592 raise NoSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000593 d2 = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000594 d = self._defaults.copy()
595 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000596 if "__name__" in d:
597 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000598 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000599
Łukasz Langa26d513c2010-11-10 18:57:39 +0000600 def _get(self, section, conv, option, **kwargs):
601 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000602
Łukasz Langa26d513c2010-11-10 18:57:39 +0000603 def getint(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000604 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000605 return self._get(section, int, option, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000606 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000607 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000608 raise
609 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000610 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000611
Łukasz Langa26d513c2010-11-10 18:57:39 +0000612 def getfloat(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000613 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000614 return self._get(section, float, option, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000615 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000616 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000617 raise
618 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000619 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000620
Łukasz Langa26d513c2010-11-10 18:57:39 +0000621 def getboolean(self, section, option, *, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000622 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000623 return self._get(section, self._convert_to_boolean, option,
624 vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000625 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000626 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000627 raise
628 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000629 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000630
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000631 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000632 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000633
Eric S. Raymond417c4892000-07-10 18:11:00 +0000634 def has_option(self, section, option):
635 """Check for the existence of a given option in a given section."""
Łukasz Langac264c092010-11-20 16:15:37 +0000636 if not section or section == self._default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000637 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000638 return option in self._defaults
639 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000640 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000641 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000642 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000643 return (option in self._sections[section]
644 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000645
Fred Drake03c44a32010-02-19 06:08:41 +0000646 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000647 """Set an option."""
Łukasz Langac264c092010-11-20 16:15:37 +0000648 if not section or section == self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000649 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000650 else:
651 try:
Fred Drakefce65572002-10-25 18:08:18 +0000652 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000653 except KeyError:
654 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000655 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000656
Georg Brandl96a60ae2010-07-28 13:13:46 +0000657 def write(self, fp, space_around_delimiters=True):
658 """Write an .ini-format representation of the configuration state.
659
660 If `space_around_delimiters' is True (the default), delimiters
661 between keys and values are surrounded by spaces.
662 """
663 if space_around_delimiters:
664 d = " {} ".format(self._delimiters[0])
665 else:
666 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000667 if self._defaults:
Łukasz Langac264c092010-11-20 16:15:37 +0000668 self._write_section(fp, self._default_section,
669 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000670 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000671 self._write_section(fp, section,
672 self._sections[section].items(), d)
673
674 def _write_section(self, fp, section_name, section_items, delimiter):
675 """Write a single section to the specified `fp'."""
676 fp.write("[{}]\n".format(section_name))
677 for key, value in section_items:
678 if key == "__name__":
679 continue
Łukasz Langa26d513c2010-11-10 18:57:39 +0000680 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000681 value = delimiter + str(value).replace('\n', '\n\t')
682 else:
683 value = ""
684 fp.write("{}{}\n".format(key, value))
685 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000686
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000687 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000688 """Remove an option."""
Łukasz Langac264c092010-11-20 16:15:37 +0000689 if not section or section == self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000690 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000691 else:
692 try:
Fred Drakefce65572002-10-25 18:08:18 +0000693 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000694 except KeyError:
695 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000696 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000697 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000698 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000699 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000700 return existed
701
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000702 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000703 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000704 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000705 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000706 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000707 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000708 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000709
Łukasz Langa26d513c2010-11-10 18:57:39 +0000710 def __getitem__(self, key):
Łukasz Langac264c092010-11-20 16:15:37 +0000711 if key != self._default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000712 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000713 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000714
715 def __setitem__(self, key, value):
716 # To conform with the mapping protocol, overwrites existing values in
717 # the section.
718
719 # XXX this is not atomic if read_dict fails at any point. Then again,
720 # no update method in configparser is atomic in this implementation.
721 self.remove_section(key)
722 self.read_dict({key: value})
723
724 def __delitem__(self, key):
Łukasz Langac264c092010-11-20 16:15:37 +0000725 if key == self._default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000726 raise ValueError("Cannot remove the default section.")
727 if not self.has_section(key):
728 raise KeyError(key)
729 self.remove_section(key)
730
731 def __contains__(self, key):
Łukasz Langac264c092010-11-20 16:15:37 +0000732 return key == self._default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000733
734 def __len__(self):
735 return len(self._sections) + 1 # the default section
736
737 def __iter__(self):
738 # XXX does it break when underlying container state changed?
Łukasz Langac264c092010-11-20 16:15:37 +0000739 return itertools.chain((self._default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000740
Fred Drakefce65572002-10-25 18:08:18 +0000741 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000742 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000743
Fred Drakea4923622010-08-09 12:52:45 +0000744 Each section in a configuration file contains a header, indicated by
745 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000746 `name' and `value' delimited with a specific substring (`=' or `:' by
747 default).
748
Fred Drakea4923622010-08-09 12:52:45 +0000749 Values can span multiple lines, as long as they are indented deeper
750 than the first line of the value. Depending on the parser's mode, blank
751 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000752
753 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000754 characters (`#' and `;' by default). Comments may appear on their own
755 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000756 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000757 """
Fred Drakea4923622010-08-09 12:52:45 +0000758 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000759 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +0000760 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000761 optname = None
762 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000763 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000764 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000765 for lineno, line in enumerate(fp, start=1):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000766 # strip full line comments
Georg Brandl96a60ae2010-07-28 13:13:46 +0000767 comment_start = None
768 for prefix in self._startonly_comment_prefixes:
769 if line.strip().startswith(prefix):
770 comment_start = 0
771 break
772 # strip inline comments
773 for prefix in self._comment_prefixes:
774 index = line.find(prefix)
775 if index == 0 or (index > 0 and line[index-1].isspace()):
776 comment_start = index
777 break
778 value = line[:comment_start].strip()
779 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +0000780 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000781 # add empty line to the value, but only if there was no
782 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +0000783 if (comment_start is None and
784 cursect is not None and
785 optname and
786 cursect[optname] is not None):
787 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +0000788 else:
789 # empty line marks end of value
790 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000791 continue
792 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +0000793 first_nonspace = self.NONSPACECRE.search(line)
794 cur_indent_level = first_nonspace.start() if first_nonspace else 0
795 if (cursect is not None and optname and
796 cur_indent_level > indent_level):
797 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000798 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000799 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000800 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000801 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +0000802 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000803 if mo:
804 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000805 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +0000806 if self._strict and sectname in elements_added:
807 raise DuplicateSectionError(sectname, fpname,
808 lineno)
Fred Drakefce65572002-10-25 18:08:18 +0000809 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +0000810 elements_added.add(sectname)
Łukasz Langac264c092010-11-20 16:15:37 +0000811 elif sectname == self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000812 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000813 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000814 cursect = self._dict()
815 cursect['__name__'] = sectname
Fred Drakefce65572002-10-25 18:08:18 +0000816 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +0000817 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +0000818 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000819 # So sections can't start with a continuation line
820 optname = None
821 # no section header in the file?
822 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000823 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000824 # an option line?
825 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000826 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000827 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000828 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +0000829 if not optname:
830 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000831 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +0000832 if (self._strict and
833 (sectname, optname) in elements_added):
834 raise DuplicateOptionError(sectname, optname,
835 fpname, lineno)
836 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +0000837 # This check is fine because the OPTCRE cannot
838 # match if it would set optval to None
839 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +0000840 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000841 # allow empty values
842 if optval == '""':
843 optval = ''
844 cursect[optname] = [optval]
845 else:
846 # valueless option handling
847 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000848 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000849 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000850 # exception but keep going. the exception will be
851 # raised at the end of the file and will contain a
852 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +0000853 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000854 # if any parsing errors occurred, raise an exception
855 if e:
856 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +0000857 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +0000858
Georg Brandl96a60ae2010-07-28 13:13:46 +0000859 def _join_multiline_values(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000860 all_sections = itertools.chain((self._defaults,),
861 self._sections.values())
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000862 for options in all_sections:
863 for name, val in options.items():
864 if isinstance(val, list):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000865 options[name] = '\n'.join(val).rstrip()
Fred Drakefce65572002-10-25 18:08:18 +0000866
Georg Brandl96a60ae2010-07-28 13:13:46 +0000867 def _handle_error(self, exc, fpname, lineno, line):
868 if not exc:
869 exc = ParsingError(fpname)
870 exc.append(lineno, repr(line))
871 return exc
872
Fred Drakecc645b92010-09-04 04:35:34 +0000873 def _unify_values(self, section, vars):
874 """Create a copy of the DEFAULTSECT with values from a specific
875 `section' and the `vars' dictionary. If provided, values in `vars'
876 take precendence.
Fred Drakefce65572002-10-25 18:08:18 +0000877 """
878 d = self._defaults.copy()
879 try:
880 d.update(self._sections[section])
881 except KeyError:
Łukasz Langac264c092010-11-20 16:15:37 +0000882 if section != self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000883 raise NoSectionError(section)
884 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +0000885 if vars:
886 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +0000887 if value is not None:
888 value = str(value)
David Goodger68a1abd2004-10-03 15:40:25 +0000889 d[self.optionxform(key)] = value
Fred Drakecc645b92010-09-04 04:35:34 +0000890 return d
891
892 def _convert_to_boolean(self, value):
893 """Return a boolean value translating from other types if necessary.
894 """
895 if value.lower() not in self.BOOLEAN_STATES:
896 raise ValueError('Not a boolean: %s' % value)
897 return self.BOOLEAN_STATES[value.lower()]
898
Łukasz Langa26d513c2010-11-10 18:57:39 +0000899 def _validate_value_type(self, value):
900 """Raises a TypeError for non-string values.
901
902 The only legal non-string value if we allow valueless
903 options is None, so we need to check if the value is a
904 string if:
905 - we do not allow valueless options, or
906 - we allow valueless options but the value is not None
907
908 For compatibility reasons this method is not used in classic set()
909 for RawConfigParsers and ConfigParsers. It is invoked in every
910 case for mapping protocol access and in SafeConfigParser.set().
911 """
912 if not self._allow_no_value or value:
913 if not isinstance(value, str):
914 raise TypeError("option values must be strings")
915
916
Fred Drakecc645b92010-09-04 04:35:34 +0000917
918class ConfigParser(RawConfigParser):
919 """ConfigParser implementing interpolation."""
920
Łukasz Langa26d513c2010-11-10 18:57:39 +0000921 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000922 """Get an option value for a given section.
923
924 If `vars' is provided, it must be a dictionary. The option is looked up
925 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000926 If the key is not found and `fallback' is provided, it is used as
927 a fallback value. `None' can be provided as a `fallback' value.
Fred Drakecc645b92010-09-04 04:35:34 +0000928
929 All % interpolations are expanded in the return values, unless the
930 optional argument `raw' is true. Values for interpolation keys are
931 looked up in the same manner as the option.
932
Łukasz Langa26d513c2010-11-10 18:57:39 +0000933 Arguments `raw', `vars', and `fallback' are keyword only.
934
Fred Drakecc645b92010-09-04 04:35:34 +0000935 The section DEFAULT is special.
936 """
937 try:
938 d = self._unify_values(section, vars)
939 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000940 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000941 raise
942 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000943 return fallback
Fred Drakefce65572002-10-25 18:08:18 +0000944 option = self.optionxform(option)
945 try:
946 value = d[option]
947 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000948 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000949 raise NoOptionError(option, section)
950 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000951 return fallback
Fred Drakefce65572002-10-25 18:08:18 +0000952
Fred Drake03c44a32010-02-19 06:08:41 +0000953 if raw or value is None:
Fred Drakefce65572002-10-25 18:08:18 +0000954 return value
955 else:
956 return self._interpolate(section, option, value, d)
957
Łukasz Langa26d513c2010-11-10 18:57:39 +0000958 def getint(self, section, option, *, raw=False, vars=None,
959 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000960 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000961 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000962 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000963 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000964 raise
965 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000966 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000967
Łukasz Langa26d513c2010-11-10 18:57:39 +0000968 def getfloat(self, section, option, *, raw=False, vars=None,
969 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000970 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000971 return self._get(section, float, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000972 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000973 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000974 raise
975 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000976 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000977
Łukasz Langa26d513c2010-11-10 18:57:39 +0000978 def getboolean(self, section, option, *, raw=False, vars=None,
979 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000980 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000981 return self._get(section, self._convert_to_boolean, option,
982 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000983 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000984 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000985 raise
986 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000987 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000988
Neal Norwitzf680cc42002-12-17 01:56:47 +0000989 def items(self, section, raw=False, vars=None):
Fred Drakea4923622010-08-09 12:52:45 +0000990 """Return a list of (name, value) tuples for each option in a section.
Fred Drakefce65572002-10-25 18:08:18 +0000991
992 All % interpolations are expanded in the return values, based on the
993 defaults passed into the constructor, unless the optional argument
994 `raw' is true. Additional substitutions may be provided using the
995 `vars' argument, which must be a dictionary whose contents overrides
996 any pre-existing defaults.
997
998 The section DEFAULT is special.
999 """
1000 d = self._defaults.copy()
1001 try:
1002 d.update(self._sections[section])
1003 except KeyError:
Łukasz Langac264c092010-11-20 16:15:37 +00001004 if section != self._default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001005 raise NoSectionError(section)
1006 # Update with the entry specific variables
1007 if vars:
David Goodger68a1abd2004-10-03 15:40:25 +00001008 for key, value in vars.items():
1009 d[self.optionxform(key)] = value
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001010 options = list(d.keys())
Fred Drakedf393bd2002-10-25 20:41:30 +00001011 if "__name__" in options:
1012 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +00001013 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +00001014 return [(option, d[option])
1015 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +00001016 else:
Fred Drake8c4da532003-10-21 16:45:00 +00001017 return [(option, self._interpolate(section, option, d[option], d))
1018 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +00001019
1020 def _interpolate(self, section, option, rawval, vars):
1021 # do the string interpolation
1022 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +00001023 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +00001024 while depth: # Loop through this until it's done
1025 depth -= 1
Fred Drake03c44a32010-02-19 06:08:41 +00001026 if value and "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +00001027 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +00001028 try:
1029 value = value % vars
Guido van Rossumb940e112007-01-10 16:19:56 +00001030 except KeyError as e:
Fred Drakee2c64912002-12-31 17:23:27 +00001031 raise InterpolationMissingOptionError(
Brett Cannonca477b22007-03-21 22:26:20 +00001032 option, section, rawval, e.args[0])
Fred Drakefce65572002-10-25 18:08:18 +00001033 else:
1034 break
Fred Drake03c44a32010-02-19 06:08:41 +00001035 if value and "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +00001036 raise InterpolationDepthError(option, section, rawval)
1037 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +00001038
Fred Drakebc12b012004-05-18 02:25:51 +00001039 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
1040
1041 def _interpolation_replace(self, match):
1042 s = match.group(1)
1043 if s is None:
1044 return match.group()
1045 else:
1046 return "%%(%s)s" % self.optionxform(s)
1047
Fred Drake0eebd5c2002-10-25 21:52:00 +00001048
1049class SafeConfigParser(ConfigParser):
Georg Brandl96a60ae2010-07-28 13:13:46 +00001050 """ConfigParser implementing sane interpolation."""
Fred Drake0eebd5c2002-10-25 21:52:00 +00001051
1052 def _interpolate(self, section, option, rawval, vars):
1053 # do the string interpolation
1054 L = []
1055 self._interpolate_some(option, L, rawval, section, vars, 1)
1056 return ''.join(L)
1057
Guido van Rossumd8faa362007-04-27 19:54:29 +00001058 _interpvar_re = re.compile(r"%\(([^)]+)\)s")
Fred Drake0eebd5c2002-10-25 21:52:00 +00001059
1060 def _interpolate_some(self, option, accum, rest, section, map, depth):
1061 if depth > MAX_INTERPOLATION_DEPTH:
1062 raise InterpolationDepthError(option, section, rest)
1063 while rest:
1064 p = rest.find("%")
1065 if p < 0:
1066 accum.append(rest)
1067 return
1068 if p > 0:
1069 accum.append(rest[:p])
1070 rest = rest[p:]
1071 # p is no longer used
1072 c = rest[1:2]
1073 if c == "%":
1074 accum.append("%")
1075 rest = rest[2:]
1076 elif c == "(":
Guido van Rossumd8faa362007-04-27 19:54:29 +00001077 m = self._interpvar_re.match(rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +00001078 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +00001079 raise InterpolationSyntaxError(option, section,
1080 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +00001081 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +00001082 rest = rest[m.end():]
1083 try:
1084 v = map[var]
1085 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +00001086 raise InterpolationMissingOptionError(
1087 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +00001088 if "%" in v:
1089 self._interpolate_some(option, accum, v,
1090 section, map, depth + 1)
1091 else:
1092 accum.append(v)
1093 else:
1094 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +00001095 option, section,
Fred Drakea4923622010-08-09 12:52:45 +00001096 "'%%' must be followed by '%%' or '(', "
1097 "found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +00001098
Fred Drake03c44a32010-02-19 06:08:41 +00001099 def set(self, section, option, value=None):
David Goodger1cbf2062004-10-03 15:55:09 +00001100 """Set an option. Extend ConfigParser.set: check for string values."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001101 self._validate_value_type(value)
Fred Drakea4923622010-08-09 12:52:45 +00001102 # check for bad percent signs
1103 if value:
1104 tmp_value = value.replace('%%', '') # escaped percent signs
1105 tmp_value = self._interpvar_re.sub('', tmp_value) # valid syntax
1106 if '%' in tmp_value:
1107 raise ValueError("invalid interpolation syntax in %r at "
1108 "position %d" % (value, tmp_value.find('%')))
David Goodger1cbf2062004-10-03 15:55:09 +00001109 ConfigParser.set(self, section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001110
1111
1112class SectionProxy(MutableMapping):
1113 """A proxy for a single section from a parser."""
1114
1115 _noname = ("__name__ special key access and modification "
1116 "not supported through the mapping interface.")
1117
1118 def __init__(self, parser, section_name):
1119 """Creates a view on a section named `section_name` in `parser`."""
1120 self._parser = parser
1121 self._section = section_name
1122 self.getint = functools.partial(self._parser.getint,
1123 self._section)
1124 self.getfloat = functools.partial(self._parser.getfloat,
1125 self._section)
1126 self.getboolean = functools.partial(self._parser.getboolean,
1127 self._section)
1128
1129 def __repr__(self):
1130 return '<Section: {}>'.format(self._section)
1131
1132 def __getitem__(self, key):
1133 if key == '__name__':
1134 raise ValueError(self._noname)
1135 if not self._parser.has_option(self._section, key):
1136 raise KeyError(key)
1137 return self._parser.get(self._section, key)
1138
1139 def __setitem__(self, key, value):
1140 if key == '__name__':
1141 raise ValueError(self._noname)
1142 self._parser._validate_value_type(value)
1143 return self._parser.set(self._section, key, value)
1144
1145 def __delitem__(self, key):
1146 if key == '__name__':
1147 raise ValueError(self._noname)
1148 if not self._parser.has_option(self._section, key):
1149 raise KeyError(key)
1150 return self._parser.remove_option(self._section, key)
1151
1152 def __contains__(self, key):
1153 if key == '__name__':
1154 return False
1155 return self._parser.has_option(self._section, key)
1156
1157 def __len__(self):
1158 # __name__ is properly hidden by .options()
1159 # XXX weak performance
1160 return len(self._parser.options(self._section))
1161
1162 def __iter__(self):
1163 # __name__ is properly hidden by .options()
1164 # XXX weak performance
1165 # XXX does not break when underlying container state changed
1166 return self._parser.options(self._section).__iter__()