blob: eafcea3382f18c6ed33c4a1c25956c3acd5dae28 [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
Guido van Rossum3d209861997-12-09 16:10:31 +00007Intrinsic defaults can be specified by passing them into the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00008SafeConfigParser constructor as a dictionary.
Guido van Rossum3d209861997-12-09 16:10:31 +00009
10class:
11
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000012SafeConfigParser -- responsible for parsing a list of
13 configuration files, and managing the parsed database.
Guido van Rossum3d209861997-12-09 16:10:31 +000014
15 methods:
16
Fred Drakecc645b92010-09-04 04:35:34 +000017 __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
18 delimiters=('=', ':'), comment_prefixes=_COMPATIBLE,
19 strict=False, empty_lines_in_values=True):
Georg Brandl96a60ae2010-07-28 13:13:46 +000020 Create the parser. When `defaults' is given, it is initialized into the
21 dictionary or intrinsic defaults. The keys must be strings, the values
Łukasz Langa5c863392010-11-21 13:41:35 +000022 must be appropriate for %()s string interpolation.
Georg Brandl96a60ae2010-07-28 13:13:46 +000023
24 When `dict_type' is given, it will be used to create the dictionary
25 objects for the list of sections, for the options within a section, and
26 for the default values.
27
28 When `delimiters' is given, it will be used as the set of substrings
29 that divide keys from values.
30
31 When `comment_prefixes' is given, it will be used as the set of
32 substrings that prefix comments in a line.
33
Fred Drakea4923622010-08-09 12:52:45 +000034 When `strict` is True, the parser won't allow for any section or option
35 duplicates while reading from a single source (file, string or
36 dictionary). Default is False.
37
Georg Brandl96a60ae2010-07-28 13:13:46 +000038 When `empty_lines_in_values' is False (default: True), each empty line
39 marks the end of an option. Otherwise, internal empty lines of
40 a multiline option are kept as part of the value.
41
42 When `allow_no_value' is True (default: False), options without
43 values are accepted; the value presented for these is None.
Guido van Rossum3d209861997-12-09 16:10:31 +000044
Barry Warsawf09f6a51999-01-26 22:01:37 +000045 sections()
Georg Brandl96a60ae2010-07-28 13:13:46 +000046 Return all the configuration section names, sans DEFAULT.
Guido van Rossum3d209861997-12-09 16:10:31 +000047
Guido van Rossuma5a24b71999-10-04 19:58:22 +000048 has_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000049 Return whether the given section exists.
Guido van Rossuma5a24b71999-10-04 19:58:22 +000050
Eric S. Raymond649685a2000-07-14 14:28:22 +000051 has_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +000052 Return whether the given option exists in the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +000053
Barry Warsawf09f6a51999-01-26 22:01:37 +000054 options(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +000055 Return list of configuration options for the named section.
Guido van Rossum3d209861997-12-09 16:10:31 +000056
Georg Brandl8dcaa732010-07-29 12:17:40 +000057 read(filenames, encoding=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000058 Read and parse the list of named configuration files, given by
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000059 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000060 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000061
Fred Drakea4923622010-08-09 12:52:45 +000062 read_file(f, filename=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000063 Read and parse one configuration file, given as a file object.
Fred Drakea4923622010-08-09 12:52:45 +000064 The filename defaults to f.name; it is only used in error
65 messages (if f has no `name' attribute, the string `<???>' is used).
66
67 read_string(string)
68 Read configuration from a given string.
69
70 read_dict(dictionary)
71 Read configuration from a dictionary. Keys are section names,
72 values are dictionaries with keys and values that should be present
73 in the section. If the used dictionary type preserves order, sections
Fred Drakecc645b92010-09-04 04:35:34 +000074 and their keys will be added in order. Values are automatically
75 converted to strings.
Guido van Rossum3d209861997-12-09 16:10:31 +000076
Łukasz Langa26d513c2010-11-10 18:57:39 +000077 get(section, option, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000078 Return a string value for the named option. All % interpolations are
Barry Warsawf09f6a51999-01-26 22:01:37 +000079 expanded in the return values, based on the defaults passed into the
80 constructor and the DEFAULT section. Additional substitutions may be
81 provided using the `vars' argument, which must be a dictionary whose
Fred Drakecc645b92010-09-04 04:35:34 +000082 contents override any pre-existing defaults. If `option' is a key in
83 `vars', the value from `vars' is used.
Guido van Rossum3d209861997-12-09 16:10:31 +000084
Łukasz Langa26d513c2010-11-10 18:57:39 +000085 getint(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000086 Like get(), but convert value to an integer.
Guido van Rossum3d209861997-12-09 16:10:31 +000087
Łukasz Langa26d513c2010-11-10 18:57:39 +000088 getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000089 Like get(), but convert value to a float.
Guido van Rossum3d209861997-12-09 16:10:31 +000090
Łukasz Langa26d513c2010-11-10 18:57:39 +000091 getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
Georg Brandl96a60ae2010-07-28 13:13:46 +000092 Like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +000093 insensitively defined as 0, false, no, off for False, and 1, true,
94 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +000095
Neal Norwitzf680cc42002-12-17 01:56:47 +000096 items(section, raw=False, vars=None)
Georg Brandl96a60ae2010-07-28 13:13:46 +000097 Return a list of tuples with (name, value) for each option
Fred Drake2ca041f2002-09-27 15:49:56 +000098 in the section.
99
Eric S. Raymond649685a2000-07-14 14:28:22 +0000100 remove_section(section)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000101 Remove the given file section and all its options.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000102
103 remove_option(section, option)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000104 Remove the given option from the given section.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000105
106 set(section, option, value)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000107 Set the given option.
Eric S. Raymond649685a2000-07-14 14:28:22 +0000108
Georg Brandl96a60ae2010-07-28 13:13:46 +0000109 write(fp, space_around_delimiters=True)
110 Write the configuration state in .ini format. If
111 `space_around_delimiters' is True (the default), delimiters
112 between keys and values are surrounded by spaces.
Guido van Rossum3d209861997-12-09 16:10:31 +0000113"""
114
Łukasz Langa26d513c2010-11-10 18:57:39 +0000115from collections import MutableMapping, OrderedDict as _default_dict
116import functools
Fred Drakea4923622010-08-09 12:52:45 +0000117import io
Łukasz Langa26d513c2010-11-10 18:57:39 +0000118import itertools
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000119import re
Georg Brandl96a60ae2010-07-28 13:13:46 +0000120import sys
Fred Drakea4923622010-08-09 12:52:45 +0000121import warnings
Guido van Rossum3d209861997-12-09 16:10:31 +0000122
Fred Drakea4923622010-08-09 12:52:45 +0000123__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
124 "NoOptionError", "InterpolationError", "InterpolationDepthError",
Fred Drake8d5dd982002-12-30 23:51:45 +0000125 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000126 "MissingSectionHeaderError",
127 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000128 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000129
Guido van Rossum3d209861997-12-09 16:10:31 +0000130DEFAULTSECT = "DEFAULT"
131
Fred Drake2a37f9f2000-09-27 22:43:54 +0000132MAX_INTERPOLATION_DEPTH = 10
133
Guido van Rossum3d209861997-12-09 16:10:31 +0000134
Tim Peters88869f92001-01-14 23:36:06 +0000135
Guido van Rossum3d209861997-12-09 16:10:31 +0000136# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000137class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000138 """Base class for ConfigParser exceptions."""
139
Guido van Rossum360e4b82007-05-14 22:51:27 +0000140 def _get_message(self):
141 """Getter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000142 BaseException.
143 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000144 return self.__message
145
146 def _set_message(self, value):
147 """Setter for 'message'; needed only to override deprecation in
Georg Brandl96a60ae2010-07-28 13:13:46 +0000148 BaseException.
149 """
Guido van Rossum360e4b82007-05-14 22:51:27 +0000150 self.__message = value
151
152 # BaseException.message has been deprecated since Python 2.6. To prevent
Fred Drakea4923622010-08-09 12:52:45 +0000153 # DeprecationWarning from popping up over this pre-existing attribute, use
154 # a new property that takes lookup precedence.
Guido van Rossum360e4b82007-05-14 22:51:27 +0000155 message = property(_get_message, _set_message)
156
Guido van Rossum3d209861997-12-09 16:10:31 +0000157 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000158 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000159 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000160
Guido van Rossum3d209861997-12-09 16:10:31 +0000161 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000162 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000163
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000164 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000165
Georg Brandl96a60ae2010-07-28 13:13:46 +0000166
Guido van Rossum3d209861997-12-09 16:10:31 +0000167class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000168 """Raised when no section matches a requested option."""
169
Guido van Rossum3d209861997-12-09 16:10:31 +0000170 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000171 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000172 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000173 self.args = (section, )
Guido van Rossum3d209861997-12-09 16:10:31 +0000174
Georg Brandl96a60ae2010-07-28 13:13:46 +0000175
Guido van Rossum3d209861997-12-09 16:10:31 +0000176class DuplicateSectionError(Error):
Fred Drakea4923622010-08-09 12:52:45 +0000177 """Raised when a section is repeated in an input source.
Fred Drake8d5dd982002-12-30 23:51:45 +0000178
Fred Drakea4923622010-08-09 12:52:45 +0000179 Possible repetitions that raise this exception are: multiple creation
180 using the API or in strict parsers when a section is found more than once
181 in a single input file, string or dictionary.
182 """
183
184 def __init__(self, section, source=None, lineno=None):
185 msg = [repr(section), " already exists"]
186 if source is not None:
187 message = ["While reading from ", source]
188 if lineno is not None:
189 message.append(" [line {0:2d}]".format(lineno))
190 message.append(": section ")
191 message.extend(msg)
192 msg = message
193 else:
194 msg.insert(0, "Section ")
195 Error.__init__(self, "".join(msg))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 self.section = section
Fred Drakea4923622010-08-09 12:52:45 +0000197 self.source = source
198 self.lineno = lineno
199 self.args = (section, source, lineno)
200
201
202class DuplicateOptionError(Error):
203 """Raised by strict parsers when an option is repeated in an input source.
204
205 Current implementation raises this exception only when an option is found
206 more than once in a single file, string or dictionary.
207 """
208
209 def __init__(self, section, option, source=None, lineno=None):
210 msg = [repr(option), " in section ", repr(section),
211 " already exists"]
212 if source is not None:
213 message = ["While reading from ", source]
214 if lineno is not None:
215 message.append(" [line {0:2d}]".format(lineno))
216 message.append(": option ")
217 message.extend(msg)
218 msg = message
219 else:
220 msg.insert(0, "Option ")
221 Error.__init__(self, "".join(msg))
222 self.section = section
223 self.option = option
224 self.source = source
225 self.lineno = lineno
226 self.args = (section, option, source, lineno)
Guido van Rossum3d209861997-12-09 16:10:31 +0000227
Georg Brandl96a60ae2010-07-28 13:13:46 +0000228
Guido van Rossum3d209861997-12-09 16:10:31 +0000229class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000230 """A requested option was not found."""
231
Guido van Rossum3d209861997-12-09 16:10:31 +0000232 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000233 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 (option, section))
235 self.option = option
236 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000237 self.args = (option, section)
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 InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000241 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000242
Fred Drakee2c64912002-12-31 17:23:27 +0000243 def __init__(self, option, section, msg):
244 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 self.option = option
246 self.section = section
Michael Foordbd6c0792010-07-25 23:09:25 +0000247 self.args = (option, section, msg)
Guido van Rossum3d209861997-12-09 16:10:31 +0000248
Georg Brandl96a60ae2010-07-28 13:13:46 +0000249
Fred Drakee2c64912002-12-31 17:23:27 +0000250class InterpolationMissingOptionError(InterpolationError):
251 """A string substitution required a setting which was not available."""
252
253 def __init__(self, option, section, rawval, reference):
254 msg = ("Bad value substitution:\n"
255 "\tsection: [%s]\n"
256 "\toption : %s\n"
257 "\tkey : %s\n"
258 "\trawval : %s\n"
259 % (section, option, reference, rawval))
260 InterpolationError.__init__(self, option, section, msg)
261 self.reference = reference
Michael Foordbd6c0792010-07-25 23:09:25 +0000262 self.args = (option, section, rawval, reference)
Fred Drakee2c64912002-12-31 17:23:27 +0000263
Georg Brandl96a60ae2010-07-28 13:13:46 +0000264
Fred Drakee2c64912002-12-31 17:23:27 +0000265class InterpolationSyntaxError(InterpolationError):
Fred Drakea4923622010-08-09 12:52:45 +0000266 """Raised when the source text contains invalid syntax.
267
268 Current implementation raises this exception only for SafeConfigParser
269 instances when the source text into which substitutions are made
270 does not conform to the required syntax.
271 """
Neal Norwitzce1d9442002-12-30 23:38:47 +0000272
Georg Brandl96a60ae2010-07-28 13:13:46 +0000273
Fred Drakee2c64912002-12-31 17:23:27 +0000274class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000275 """Raised when substitutions are nested too deeply."""
276
Fred Drake2a37f9f2000-09-27 22:43:54 +0000277 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000278 msg = ("Value interpolation too deeply recursive:\n"
279 "\tsection: [%s]\n"
280 "\toption : %s\n"
281 "\trawval : %s\n"
282 % (section, option, rawval))
283 InterpolationError.__init__(self, option, section, msg)
Michael Foordbd6c0792010-07-25 23:09:25 +0000284 self.args = (option, section, rawval)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000285
Georg Brandl96a60ae2010-07-28 13:13:46 +0000286
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000287class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000288 """Raised when a configuration file does not follow legal syntax."""
289
Fred Drakea4923622010-08-09 12:52:45 +0000290 def __init__(self, source=None, filename=None):
291 # Exactly one of `source'/`filename' arguments has to be given.
292 # `filename' kept for compatibility.
293 if filename and source:
294 raise ValueError("Cannot specify both `filename' and `source'. "
295 "Use `source'.")
296 elif not filename and not source:
297 raise ValueError("Required argument `source' not given.")
298 elif filename:
299 source = filename
300 Error.__init__(self, 'Source contains parsing errors: %s' % source)
301 self.source = source
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000302 self.errors = []
Fred Drakea4923622010-08-09 12:52:45 +0000303 self.args = (source, )
304
305 @property
306 def filename(self):
307 """Deprecated, use `source'."""
308 warnings.warn(
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000309 "The 'filename' attribute will be removed in future versions. "
Fred Drakea4923622010-08-09 12:52:45 +0000310 "Use 'source' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000311 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000312 )
313 return self.source
314
315 @filename.setter
316 def filename(self, value):
317 """Deprecated, user `source'."""
318 warnings.warn(
319 "The '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 self.source = value
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000324
325 def append(self, lineno, line):
326 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000327 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000328
Georg Brandl96a60ae2010-07-28 13:13:46 +0000329
Fred Drake2a37f9f2000-09-27 22:43:54 +0000330class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000331 """Raised when a key-value pair is found before any section header."""
332
Fred Drake2a37f9f2000-09-27 22:43:54 +0000333 def __init__(self, filename, lineno, line):
334 Error.__init__(
335 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000336 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000337 (filename, lineno, line))
Fred Drakea4923622010-08-09 12:52:45 +0000338 self.source = filename
Fred Drake2a37f9f2000-09-27 22:43:54 +0000339 self.lineno = lineno
340 self.line = line
Michael Foordbd6c0792010-07-25 23:09:25 +0000341 self.args = (filename, lineno, line)
Guido van Rossum3d209861997-12-09 16:10:31 +0000342
Georg Brandl96a60ae2010-07-28 13:13:46 +0000343
Fred Drakecc645b92010-09-04 04:35:34 +0000344# Used in parsers to denote selecting a backwards-compatible inline comment
345# character behavior (; and # are comments at the start of a line, but ; only
346# inline)
347_COMPATIBLE = object()
348
349# Used in parser getters to indicate the default behaviour when a specific
350# option is not found it to raise an exception. Created to enable `None' as
351# a valid fallback value.
352_UNSET = object()
353
354
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000355class Interpolation:
356 """Dummy interpolation that passes the value through with no changes."""
357
358 def before_get(self, parser, section, option, value, defaults):
359 return value
360
361 def before_set(self, parser, section, option, value):
362 return value
363
364 def before_read(self, parser, section, option, value):
365 return value
366
367 def before_write(self, parser, section, option, value):
368 return value
369
370
371class BasicInterpolation(Interpolation):
372 """Interpolation as implemented in the classic SafeConfigParser.
373
374 The option values can contain format strings which refer to other values in
375 the same section, or values in the special default section.
376
377 For example:
378
379 something: %(dir)s/whatever
380
381 would resolve the "%(dir)s" to the value of dir. All reference
382 expansions are done late, on demand. If a user needs to use a bare % in
383 a configuration file, she can escape it by writing %%. Other other % usage
384 is considered a user error and raises `InterpolationSyntaxError'."""
385
386 _KEYCRE = re.compile(r"%\(([^)]+)\)s")
387
388 def before_get(self, parser, section, option, value, defaults):
389 L = []
390 self._interpolate_some(parser, option, L, value, section, defaults, 1)
391 return ''.join(L)
392
393 def before_set(self, parser, section, option, value):
394 tmp_value = value.replace('%%', '') # escaped percent signs
395 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
396 if '%' in tmp_value:
397 raise ValueError("invalid interpolation syntax in %r at "
398 "position %d" % (value, tmp_value.find('%')))
399 return value
400
401 def _interpolate_some(self, parser, option, accum, rest, section, map,
402 depth):
403 if depth > MAX_INTERPOLATION_DEPTH:
404 raise InterpolationDepthError(option, section, rest)
405 while rest:
406 p = rest.find("%")
407 if p < 0:
408 accum.append(rest)
409 return
410 if p > 0:
411 accum.append(rest[:p])
412 rest = rest[p:]
413 # p is no longer used
414 c = rest[1:2]
415 if c == "%":
416 accum.append("%")
417 rest = rest[2:]
418 elif c == "(":
419 m = self._KEYCRE.match(rest)
420 if m is None:
421 raise InterpolationSyntaxError(option, section,
422 "bad interpolation variable reference %r" % rest)
423 var = parser.optionxform(m.group(1))
424 rest = rest[m.end():]
425 try:
426 v = map[var]
427 except KeyError:
428 raise InterpolationMissingOptionError(
429 option, section, rest, var)
430 if "%" in v:
431 self._interpolate_some(parser, option, accum, v,
432 section, map, depth + 1)
433 else:
434 accum.append(v)
435 else:
436 raise InterpolationSyntaxError(
437 option, section,
438 "'%%' must be followed by '%%' or '(', "
439 "found: %r" % (rest,))
440
441
442class ExtendedInterpolation(Interpolation):
443 """Advanced variant of interpolation, supports the syntax used by
444 `zc.buildout'. Enables interpolation between sections."""
445
446 _KEYCRE = re.compile(r"\$\{([^}]+)\}")
447
448 def before_get(self, parser, section, option, value, defaults):
449 L = []
450 self._interpolate_some(parser, option, L, value, section, defaults, 1)
451 return ''.join(L)
452
453 def before_set(self, parser, section, option, value):
454 tmp_value = value.replace('$$', '') # escaped dollar signs
455 tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
456 if '$' in tmp_value:
457 raise ValueError("invalid interpolation syntax in %r at "
458 "position %d" % (value, tmp_value.find('%')))
459 return value
460
461 def _interpolate_some(self, parser, option, accum, rest, section, map,
462 depth):
463 if depth > MAX_INTERPOLATION_DEPTH:
464 raise InterpolationDepthError(option, section, rest)
465 while rest:
466 p = rest.find("$")
467 if p < 0:
468 accum.append(rest)
469 return
470 if p > 0:
471 accum.append(rest[:p])
472 rest = rest[p:]
473 # p is no longer used
474 c = rest[1:2]
475 if c == "$":
476 accum.append("$")
477 rest = rest[2:]
478 elif c == "{":
479 m = self._KEYCRE.match(rest)
480 if m is None:
481 raise InterpolationSyntaxError(option, section,
482 "bad interpolation variable reference %r" % rest)
483 path = parser.optionxform(m.group(1)).split(':')
484 rest = rest[m.end():]
485 sect = section
486 opt = option
487 try:
488 if len(path) == 1:
489 opt = path[0]
490 v = map[opt]
491 elif len(path) == 2:
492 sect = path[0]
493 opt = path[1]
494 v = parser.get(sect, opt, raw=True)
495 else:
496 raise InterpolationSyntaxError(
497 option, section,
498 "More than one ':' found: %r" % (rest,))
499 except KeyError:
500 raise InterpolationMissingOptionError(
501 option, section, rest, var)
502 if "$" in v:
503 self._interpolate_some(parser, opt, accum, v, sect,
504 dict(parser.items(sect, raw=True)),
505 depth + 1)
506 else:
507 accum.append(v)
508 else:
509 raise InterpolationSyntaxError(
510 option, section,
511 "'$' must be followed by '$' or '{', "
512 "found: %r" % (rest,))
513
514
515class BrokenInterpolation(Interpolation):
516 """Deprecated interpolation as implemented in the classic ConfigParser.
517 Use BasicInterpolation or ExtendedInterpolation instead."""
518
519 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
520
521 def before_get(self, parser, section, option, value, vars):
522 rawval = value
523 depth = MAX_INTERPOLATION_DEPTH
524 while depth: # Loop through this until it's done
525 depth -= 1
526 if value and "%(" in value:
527 replace = functools.partial(self._interpolation_replace,
528 parser=parser)
529 value = self._KEYCRE.sub(replace, value)
530 try:
531 value = value % vars
532 except KeyError as e:
533 raise InterpolationMissingOptionError(
534 option, section, rawval, e.args[0])
535 else:
536 break
537 if value and "%(" in value:
538 raise InterpolationDepthError(option, section, rawval)
539 return value
540
541 def before_set(self, parser, section, option, value):
542 return value
543
544 @staticmethod
545 def _interpolation_replace(match, parser):
546 s = match.group(1)
547 if s is None:
548 return match.group()
549 else:
550 return "%%(%s)s" % parser.optionxform(s)
551
552
Łukasz Langa26d513c2010-11-10 18:57:39 +0000553class RawConfigParser(MutableMapping):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000554 """ConfigParser that does not do interpolation."""
555
556 # Regular expressions for parsing section headers and options
557 _SECT_TMPL = r"""
558 \[ # [
559 (?P<header>[^]]+) # very permissive!
560 \] # ]
561 """
562 _OPT_TMPL = r"""
563 (?P<option>.*?) # very permissive!
564 \s*(?P<vi>{delim})\s* # any number of space/tab,
565 # followed by any of the
566 # allowed delimiters,
567 # followed by any space/tab
568 (?P<value>.*)$ # everything up to eol
569 """
570 _OPT_NV_TMPL = r"""
571 (?P<option>.*?) # very permissive!
572 \s*(?: # any number of space/tab,
573 (?P<vi>{delim})\s* # optionally followed by
574 # any of the allowed
575 # delimiters, followed by any
576 # space/tab
577 (?P<value>.*))?$ # everything up to eol
578 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000579 # Interpolation algorithm to be used if the user does not specify another
580 _DEFAULT_INTERPOLATION = Interpolation()
Georg Brandl96a60ae2010-07-28 13:13:46 +0000581 # Compiled regular expression for matching sections
582 SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
583 # Compiled regular expression for matching options with typical separators
584 OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
585 # Compiled regular expression for matching options with optional values
586 # delimited using typical separators
587 OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
588 # Compiled regular expression for matching leading whitespace in a line
589 NONSPACECRE = re.compile(r"\S")
Fred Drakecc645b92010-09-04 04:35:34 +0000590 # Possible boolean values in the configuration.
591 BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
592 '0': False, 'no': False, 'false': False, 'off': False}
Georg Brandl96a60ae2010-07-28 13:13:46 +0000593
Fred Drake03c44a32010-02-19 06:08:41 +0000594 def __init__(self, defaults=None, dict_type=_default_dict,
Fred Drakea4923622010-08-09 12:52:45 +0000595 allow_no_value=False, *, delimiters=('=', ':'),
596 comment_prefixes=_COMPATIBLE, strict=False,
Łukasz Langac264c092010-11-20 16:15:37 +0000597 empty_lines_in_values=True,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000598 default_section=DEFAULTSECT,
599 interpolation=_UNSET):
600
601 if self.__class__ is RawConfigParser:
602 warnings.warn(
603 "The RawConfigParser class will be removed in future versions."
604 " Use 'SafeConfigParser(interpolation=None)' instead.",
605 DeprecationWarning, stacklevel=2
606 )
Thomas Wouters89f507f2006-12-13 04:49:30 +0000607 self._dict = dict_type
608 self._sections = self._dict()
609 self._defaults = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000610 self._proxies = self._dict()
Łukasz Langac264c092010-11-20 16:15:37 +0000611 self._proxies[default_section] = SectionProxy(self, default_section)
David Goodger68a1abd2004-10-03 15:40:25 +0000612 if defaults:
613 for key, value in defaults.items():
614 self._defaults[self.optionxform(key)] = value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000615 self._delimiters = tuple(delimiters)
616 if delimiters == ('=', ':'):
617 self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
618 else:
Fred Drakea4923622010-08-09 12:52:45 +0000619 d = "|".join(re.escape(d) for d in delimiters)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000620 if allow_no_value:
Fred Drakea4923622010-08-09 12:52:45 +0000621 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000622 re.VERBOSE)
623 else:
Fred Drakea4923622010-08-09 12:52:45 +0000624 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
Georg Brandl96a60ae2010-07-28 13:13:46 +0000625 re.VERBOSE)
Fred Drakecc645b92010-09-04 04:35:34 +0000626 if comment_prefixes is _COMPATIBLE:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000627 self._startonly_comment_prefixes = ('#',)
628 self._comment_prefixes = (';',)
629 else:
630 self._startonly_comment_prefixes = ()
631 self._comment_prefixes = tuple(comment_prefixes or ())
Fred Drakea4923622010-08-09 12:52:45 +0000632 self._strict = strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000633 self._allow_no_value = allow_no_value
Georg Brandl96a60ae2010-07-28 13:13:46 +0000634 self._empty_lines_in_values = empty_lines_in_values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000635 if interpolation is _UNSET:
636 self._interpolation = self._DEFAULT_INTERPOLATION
637 else:
638 self._interpolation = interpolation
639 self.default_section=default_section
Guido van Rossum3d209861997-12-09 16:10:31 +0000640
641 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000642 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000643
644 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000645 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000646 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000647 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000648
649 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000650 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000651
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000652 Raise DuplicateSectionError if a section by the specified name
Łukasz Langac264c092010-11-20 16:15:37 +0000653 already exists. Raise ValueError if name is DEFAULT.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000654 """
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000655 if section == self.default_section:
Łukasz Langa3a11e712010-12-03 22:15:19 +0000656 raise ValueError('Invalid section name: %r' % section)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000657
Fred Drakefce65572002-10-25 18:08:18 +0000658 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000659 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000660 self._sections[section] = self._dict()
Łukasz Langa49afa382010-11-11 19:53:23 +0000661 self._proxies[section] = SectionProxy(self, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000662
663 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000664 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000665
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000666 The DEFAULT section is not acknowledged.
667 """
Fred Drakefce65572002-10-25 18:08:18 +0000668 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000669
670 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000671 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000672 try:
Fred Drakefce65572002-10-25 18:08:18 +0000673 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000674 except KeyError:
675 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000676 opts.update(self._defaults)
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000677 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000678
Georg Brandl8dcaa732010-07-29 12:17:40 +0000679 def read(self, filenames, encoding=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000680 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000681
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000682 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000683 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000684 configuration file locations (e.g. current directory, user's
685 home directory, systemwide directory), and all existing
686 configuration files in the list will be read. A single
687 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000688
689 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000690 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000691 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000692 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000693 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000694 for filename in filenames:
695 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000696 with open(filename, encoding=encoding) as fp:
697 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000698 except IOError:
699 continue
Fred Drake82903142004-05-18 04:24:02 +0000700 read_ok.append(filename)
701 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000702
Fred Drakea4923622010-08-09 12:52:45 +0000703 def read_file(self, f, source=None):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000704 """Like read() but the argument must be a file-like object.
705
Fred Drakea4923622010-08-09 12:52:45 +0000706 The `f' argument must have a `readline' method. Optional second
707 argument is the `source' specifying the name of the file being read. If
708 not given, it is taken from f.name. If `f' has no `name' attribute,
709 `<???>' is used.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000710 """
Fred Drakea4923622010-08-09 12:52:45 +0000711 if source is None:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000712 try:
Florent Xicluna42d54452010-09-22 22:35:38 +0000713 source = f.name
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000714 except AttributeError:
Fred Drakea4923622010-08-09 12:52:45 +0000715 source = '<???>'
716 self._read(f, source)
717
718 def read_string(self, string, source='<string>'):
719 """Read configuration from a given string."""
720 sfile = io.StringIO(string)
721 self.read_file(sfile, source)
722
723 def read_dict(self, dictionary, source='<dict>'):
724 """Read configuration from a dictionary.
725
726 Keys are section names, values are dictionaries with keys and values
727 that should be present in the section. If the used dictionary type
728 preserves order, sections and their keys will be added in order.
729
730 Optional second argument is the `source' specifying the name of the
731 dictionary being read.
732 """
733 elements_added = set()
734 for section, keys in dictionary.items():
735 try:
736 self.add_section(section)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000737 except (DuplicateSectionError, ValueError):
Fred Drakea4923622010-08-09 12:52:45 +0000738 if self._strict and section in elements_added:
739 raise
740 elements_added.add(section)
741 for key, value in keys.items():
742 key = self.optionxform(key)
Fred Drakecc645b92010-09-04 04:35:34 +0000743 if value is not None:
744 value = str(value)
Fred Drakea4923622010-08-09 12:52:45 +0000745 if self._strict and (section, key) in elements_added:
746 raise DuplicateOptionError(section, key, source)
747 elements_added.add((section, key))
748 self.set(section, key, value)
749
750 def readfp(self, fp, filename=None):
751 """Deprecated, use read_file instead."""
752 warnings.warn(
753 "This method will be removed in future versions. "
754 "Use 'parser.read_file()' instead.",
Łukasz Langa49afa382010-11-11 19:53:23 +0000755 DeprecationWarning, stacklevel=2
Fred Drakea4923622010-08-09 12:52:45 +0000756 )
757 self.read_file(fp, source=filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000758
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000759 def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000760 """Get an option value for a given section.
761
762 If `vars' is provided, it must be a dictionary. The option is looked up
763 in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000764 If the key is not found and `fallback' is provided, it is used as
765 a fallback value. `None' can be provided as a `fallback' value.
766
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000767 If interpolation is enabled and the optional argument `raw' is False,
768 all interpolations are expanded in the return values.
769
770 Arguments `raw', `vars', and `fallback' are keyword only.
771
772 The section DEFAULT is special.
Fred Drakecc645b92010-09-04 04:35:34 +0000773 """
774 try:
775 d = self._unify_values(section, vars)
776 except NoSectionError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000777 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000778 raise
Fred Drakefce65572002-10-25 18:08:18 +0000779 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000780 return fallback
Fred Drakecc645b92010-09-04 04:35:34 +0000781 option = self.optionxform(option)
782 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000783 value = d[option]
Fred Drakecc645b92010-09-04 04:35:34 +0000784 except KeyError:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000785 if fallback is _UNSET:
Fred Drakefce65572002-10-25 18:08:18 +0000786 raise NoOptionError(option, section)
Fred Drakecc645b92010-09-04 04:35:34 +0000787 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000788 return fallback
Fred Drake2a37f9f2000-09-27 22:43:54 +0000789
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000790 if raw or value is None:
791 return value
792 else:
793 return self._interpolation.before_get(self, section, option, value,
794 d)
Fred Drake2ca041f2002-09-27 15:49:56 +0000795
Łukasz Langa26d513c2010-11-10 18:57:39 +0000796 def _get(self, section, conv, option, **kwargs):
797 return conv(self.get(section, option, **kwargs))
Guido van Rossum3d209861997-12-09 16:10:31 +0000798
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000799 def getint(self, section, option, *, raw=False, vars=None,
800 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000801 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000802 return self._get(section, int, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000803 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000804 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000805 raise
806 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000807 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000808
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000809 def getfloat(self, section, option, *, raw=False, vars=None,
810 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000811 try:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000812 return self._get(section, float, option, raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000813 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000814 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000815 raise
816 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000817 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000818
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000819 def getboolean(self, section, option, *, raw=False, vars=None,
820 fallback=_UNSET):
Fred Drakecc645b92010-09-04 04:35:34 +0000821 try:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000822 return self._get(section, self._convert_to_boolean, option,
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000823 raw=raw, vars=vars)
Fred Drakecc645b92010-09-04 04:35:34 +0000824 except (NoSectionError, NoOptionError):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000825 if fallback is _UNSET:
Fred Drakecc645b92010-09-04 04:35:34 +0000826 raise
827 else:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000828 return fallback
Guido van Rossum3d209861997-12-09 16:10:31 +0000829
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000830 def items(self, section, raw=False, vars=None):
831 """Return a list of (name, value) tuples for each option in a section.
832
833 All % interpolations are expanded in the return values, based on the
834 defaults passed into the constructor, unless the optional argument
835 `raw' is true. Additional substitutions may be provided using the
836 `vars' argument, which must be a dictionary whose contents overrides
837 any pre-existing defaults.
838
839 The section DEFAULT is special.
840 """
841 d = self._defaults.copy()
842 try:
843 d.update(self._sections[section])
844 except KeyError:
845 if section != self.default_section:
846 raise NoSectionError(section)
847 # Update with the entry specific variables
848 if vars:
849 for key, value in vars.items():
850 d[self.optionxform(key)] = value
Łukasz Langa24bcc612010-12-04 11:48:11 +0000851 value_getter = lambda option: self._interpolation.before_get(self,
852 section, option, d[option], d)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000853 if raw:
Łukasz Langa24bcc612010-12-04 11:48:11 +0000854 value_getter = lambda option: d[option]
855 return [(option, value_getter(option)) for option in d.keys()]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000856
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000857 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000858 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000859
Eric S. Raymond417c4892000-07-10 18:11:00 +0000860 def has_option(self, section, option):
861 """Check for the existence of a given option in a given section."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000862 if not section or section == self.default_section:
Fred Drakec2ff9052002-09-27 15:33:11 +0000863 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000864 return option in self._defaults
865 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000866 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000867 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000868 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000869 return (option in self._sections[section]
870 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000871
Fred Drake03c44a32010-02-19 06:08:41 +0000872 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000873 """Set an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000874 if value:
875 value = self._interpolation.before_set(self, section, option,
876 value)
877 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000878 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000879 else:
880 try:
Fred Drakefce65572002-10-25 18:08:18 +0000881 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000882 except KeyError:
883 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000884 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000885
Georg Brandl96a60ae2010-07-28 13:13:46 +0000886 def write(self, fp, space_around_delimiters=True):
887 """Write an .ini-format representation of the configuration state.
888
889 If `space_around_delimiters' is True (the default), delimiters
890 between keys and values are surrounded by spaces.
891 """
892 if space_around_delimiters:
893 d = " {} ".format(self._delimiters[0])
894 else:
895 d = self._delimiters[0]
Fred Drakefce65572002-10-25 18:08:18 +0000896 if self._defaults:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000897 self._write_section(fp, self.default_section,
Łukasz Langac264c092010-11-20 16:15:37 +0000898 self._defaults.items(), d)
Fred Drakefce65572002-10-25 18:08:18 +0000899 for section in self._sections:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000900 self._write_section(fp, section,
901 self._sections[section].items(), d)
902
903 def _write_section(self, fp, section_name, section_items, delimiter):
904 """Write a single section to the specified `fp'."""
905 fp.write("[{}]\n".format(section_name))
906 for key, value in section_items:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000907 value = self._interpolation.before_write(self, section_name, key,
908 value)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000909 if value is not None or not self._allow_no_value:
Georg Brandl96a60ae2010-07-28 13:13:46 +0000910 value = delimiter + str(value).replace('\n', '\n\t')
911 else:
912 value = ""
913 fp.write("{}{}\n".format(key, value))
914 fp.write("\n")
Eric S. Raymond417c4892000-07-10 18:11:00 +0000915
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000916 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000917 """Remove an option."""
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000918 if not section or section == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +0000919 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000920 else:
921 try:
Fred Drakefce65572002-10-25 18:08:18 +0000922 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000923 except KeyError:
924 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000925 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000926 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000927 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000928 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000929 return existed
930
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000931 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000932 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000933 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000934 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000935 del self._sections[section]
Łukasz Langa49afa382010-11-11 19:53:23 +0000936 del self._proxies[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000937 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000938
Łukasz Langa26d513c2010-11-10 18:57:39 +0000939 def __getitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000940 if key != self.default_section and not self.has_section(key):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000941 raise KeyError(key)
Łukasz Langa49afa382010-11-11 19:53:23 +0000942 return self._proxies[key]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000943
944 def __setitem__(self, key, value):
945 # To conform with the mapping protocol, overwrites existing values in
946 # the section.
947
948 # XXX this is not atomic if read_dict fails at any point. Then again,
949 # no update method in configparser is atomic in this implementation.
950 self.remove_section(key)
951 self.read_dict({key: value})
952
953 def __delitem__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000954 if key == self.default_section:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000955 raise ValueError("Cannot remove the default section.")
956 if not self.has_section(key):
957 raise KeyError(key)
958 self.remove_section(key)
959
960 def __contains__(self, key):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000961 return key == self.default_section or self.has_section(key)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000962
963 def __len__(self):
964 return len(self._sections) + 1 # the default section
965
966 def __iter__(self):
967 # XXX does it break when underlying container state changed?
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000968 return itertools.chain((self.default_section,), self._sections.keys())
Łukasz Langa26d513c2010-11-10 18:57:39 +0000969
Fred Drakefce65572002-10-25 18:08:18 +0000970 def _read(self, fp, fpname):
Georg Brandl96a60ae2010-07-28 13:13:46 +0000971 """Parse a sectioned configuration file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000972
Fred Drakea4923622010-08-09 12:52:45 +0000973 Each section in a configuration file contains a header, indicated by
974 a name in square brackets (`[]'), plus key/value options, indicated by
Georg Brandl96a60ae2010-07-28 13:13:46 +0000975 `name' and `value' delimited with a specific substring (`=' or `:' by
976 default).
977
Fred Drakea4923622010-08-09 12:52:45 +0000978 Values can span multiple lines, as long as they are indented deeper
979 than the first line of the value. Depending on the parser's mode, blank
980 lines may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000981
982 Configuration files may include comments, prefixed by specific
Fred Drakea4923622010-08-09 12:52:45 +0000983 characters (`#' and `;' by default). Comments may appear on their own
984 in an otherwise empty line or may be entered in lines holding values or
Georg Brandl96a60ae2010-07-28 13:13:46 +0000985 section names.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000986 """
Fred Drakea4923622010-08-09 12:52:45 +0000987 elements_added = set()
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000988 cursect = None # None, or a dictionary
Fred Drakea4923622010-08-09 12:52:45 +0000989 sectname = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000990 optname = None
991 lineno = 0
Georg Brandl96a60ae2010-07-28 13:13:46 +0000992 indent_level = 0
Brian Curtin9a27b0c2010-07-26 00:27:10 +0000993 e = None # None, or an exception
Georg Brandl96a60ae2010-07-28 13:13:46 +0000994 for lineno, line in enumerate(fp, start=1):
Georg Brandlf206d0e2010-07-29 11:56:20 +0000995 # strip full line comments
Georg Brandl96a60ae2010-07-28 13:13:46 +0000996 comment_start = None
997 for prefix in self._startonly_comment_prefixes:
998 if line.strip().startswith(prefix):
999 comment_start = 0
1000 break
1001 # strip inline comments
1002 for prefix in self._comment_prefixes:
1003 index = line.find(prefix)
1004 if index == 0 or (index > 0 and line[index-1].isspace()):
1005 comment_start = index
1006 break
1007 value = line[:comment_start].strip()
1008 if not value:
Georg Brandlf206d0e2010-07-29 11:56:20 +00001009 if self._empty_lines_in_values:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001010 # add empty line to the value, but only if there was no
1011 # comment on the line
Georg Brandlf206d0e2010-07-29 11:56:20 +00001012 if (comment_start is None and
1013 cursect is not None and
1014 optname and
1015 cursect[optname] is not None):
1016 cursect[optname].append('') # newlines added at join
Georg Brandl96a60ae2010-07-28 13:13:46 +00001017 else:
1018 # empty line marks end of value
1019 indent_level = sys.maxsize
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001020 continue
1021 # continuation line?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001022 first_nonspace = self.NONSPACECRE.search(line)
1023 cur_indent_level = first_nonspace.start() if first_nonspace else 0
1024 if (cursect is not None and optname and
1025 cur_indent_level > indent_level):
1026 cursect[optname].append(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001027 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +00001028 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001029 indent_level = cur_indent_level
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001030 # is it a section header?
Georg Brandl96a60ae2010-07-28 13:13:46 +00001031 mo = self.SECTCRE.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001032 if mo:
1033 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +00001034 if sectname in self._sections:
Fred Drakea4923622010-08-09 12:52:45 +00001035 if self._strict and sectname in elements_added:
1036 raise DuplicateSectionError(sectname, fpname,
1037 lineno)
Fred Drakefce65572002-10-25 18:08:18 +00001038 cursect = self._sections[sectname]
Fred Drakea4923622010-08-09 12:52:45 +00001039 elements_added.add(sectname)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001040 elif sectname == self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001041 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001042 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043 cursect = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +00001044 self._sections[sectname] = cursect
Łukasz Langa49afa382010-11-11 19:53:23 +00001045 self._proxies[sectname] = SectionProxy(self, sectname)
Fred Drakea4923622010-08-09 12:52:45 +00001046 elements_added.add(sectname)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001047 # So sections can't start with a continuation line
1048 optname = None
1049 # no section header in the file?
1050 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +00001051 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001052 # an option line?
1053 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001054 mo = self._optcre.match(value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001055 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +00001056 optname, vi, optval = mo.group('option', 'vi', 'value')
Georg Brandl96a60ae2010-07-28 13:13:46 +00001057 if not optname:
1058 e = self._handle_error(e, fpname, lineno, line)
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001059 optname = self.optionxform(optname.rstrip())
Fred Drakea4923622010-08-09 12:52:45 +00001060 if (self._strict and
1061 (sectname, optname) in elements_added):
1062 raise DuplicateOptionError(sectname, optname,
1063 fpname, lineno)
1064 elements_added.add((sectname, optname))
Fred Drake03c44a32010-02-19 06:08:41 +00001065 # This check is fine because the OPTCRE cannot
1066 # match if it would set optval to None
1067 if optval is not None:
Fred Drake03c44a32010-02-19 06:08:41 +00001068 optval = optval.strip()
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001069 # allow empty values
1070 if optval == '""':
1071 optval = ''
1072 cursect[optname] = [optval]
1073 else:
1074 # valueless option handling
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001075 cursect[optname] = None
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001076 else:
Georg Brandl96a60ae2010-07-28 13:13:46 +00001077 # a non-fatal parsing error occurred. set up the
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001078 # exception but keep going. the exception will be
1079 # raised at the end of the file and will contain a
1080 # list of all bogus lines
Georg Brandl96a60ae2010-07-28 13:13:46 +00001081 e = self._handle_error(e, fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00001082 # if any parsing errors occurred, raise an exception
1083 if e:
1084 raise e
Georg Brandl96a60ae2010-07-28 13:13:46 +00001085 self._join_multiline_values()
Fred Drakefce65572002-10-25 18:08:18 +00001086
Georg Brandl96a60ae2010-07-28 13:13:46 +00001087 def _join_multiline_values(self):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001088 defaults = self.default_section, self._defaults
1089 all_sections = itertools.chain((defaults,),
1090 self._sections.items())
1091 for section, options in all_sections:
Brian Curtin9a27b0c2010-07-26 00:27:10 +00001092 for name, val in options.items():
1093 if isinstance(val, list):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001094 val = '\n'.join(val).rstrip()
1095 options[name] = self._interpolation.before_read(self,
1096 section,
1097 name, val)
Fred Drakefce65572002-10-25 18:08:18 +00001098
Georg Brandl96a60ae2010-07-28 13:13:46 +00001099 def _handle_error(self, exc, fpname, lineno, line):
1100 if not exc:
1101 exc = ParsingError(fpname)
1102 exc.append(lineno, repr(line))
1103 return exc
1104
Fred Drakecc645b92010-09-04 04:35:34 +00001105 def _unify_values(self, section, vars):
1106 """Create a copy of the DEFAULTSECT with values from a specific
1107 `section' and the `vars' dictionary. If provided, values in `vars'
1108 take precendence.
Fred Drakefce65572002-10-25 18:08:18 +00001109 """
1110 d = self._defaults.copy()
1111 try:
1112 d.update(self._sections[section])
1113 except KeyError:
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001114 if section != self.default_section:
Fred Drakefce65572002-10-25 18:08:18 +00001115 raise NoSectionError(section)
1116 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +00001117 if vars:
1118 for key, value in vars.items():
Fred Drakecc645b92010-09-04 04:35:34 +00001119 if value is not None:
1120 value = str(value)
David Goodger68a1abd2004-10-03 15:40:25 +00001121 d[self.optionxform(key)] = value
Fred Drakecc645b92010-09-04 04:35:34 +00001122 return d
1123
1124 def _convert_to_boolean(self, value):
1125 """Return a boolean value translating from other types if necessary.
1126 """
1127 if value.lower() not in self.BOOLEAN_STATES:
1128 raise ValueError('Not a boolean: %s' % value)
1129 return self.BOOLEAN_STATES[value.lower()]
1130
Łukasz Langa26d513c2010-11-10 18:57:39 +00001131 def _validate_value_type(self, value):
1132 """Raises a TypeError for non-string values.
1133
1134 The only legal non-string value if we allow valueless
1135 options is None, so we need to check if the value is a
1136 string if:
1137 - we do not allow valueless options, or
1138 - we allow valueless options but the value is not None
1139
1140 For compatibility reasons this method is not used in classic set()
1141 for RawConfigParsers and ConfigParsers. It is invoked in every
1142 case for mapping protocol access and in SafeConfigParser.set().
1143 """
1144 if not self._allow_no_value or value:
1145 if not isinstance(value, str):
1146 raise TypeError("option values must be strings")
1147
1148
Fred Drakecc645b92010-09-04 04:35:34 +00001149class ConfigParser(RawConfigParser):
1150 """ConfigParser implementing interpolation."""
1151
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001152 _DEFAULT_INTERPOLATION = BrokenInterpolation()
Fred Drakecc645b92010-09-04 04:35:34 +00001153
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001154 def __init__(self, *args, **kwargs):
1155 super().__init__(*args, **kwargs)
1156 if self.__class__ is ConfigParser:
1157 warnings.warn(
1158 "The ConfigParser class will be removed in future versions."
1159 " Use SafeConfigParser instead.",
1160 DeprecationWarning, stacklevel=2
1161 )
Fred Drakebc12b012004-05-18 02:25:51 +00001162
Fred Drake0eebd5c2002-10-25 21:52:00 +00001163
1164class SafeConfigParser(ConfigParser):
Georg Brandl96a60ae2010-07-28 13:13:46 +00001165 """ConfigParser implementing sane interpolation."""
Fred Drake0eebd5c2002-10-25 21:52:00 +00001166
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001167 _DEFAULT_INTERPOLATION = BasicInterpolation()
David Goodger1cbf2062004-10-03 15:55:09 +00001168
Fred Drake03c44a32010-02-19 06:08:41 +00001169 def set(self, section, option, value=None):
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001170 """Set an option. Extends RawConfigParser.set by validating type and
1171 interpolation syntax on the value."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001172 self._validate_value_type(value)
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001173 super().set(section, option, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001174
1175
1176class SectionProxy(MutableMapping):
1177 """A proxy for a single section from a parser."""
1178
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001179 def __init__(self, parser, name):
1180 """Creates a view on a section of the specified `name` in `parser`."""
Łukasz Langa26d513c2010-11-10 18:57:39 +00001181 self._parser = parser
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001182 self._name = name
Łukasz Langa26d513c2010-11-10 18:57:39 +00001183 self.getint = functools.partial(self._parser.getint,
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001184 self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001185 self.getfloat = functools.partial(self._parser.getfloat,
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001186 self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001187 self.getboolean = functools.partial(self._parser.getboolean,
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001188 self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001189
1190 def __repr__(self):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001191 return '<Section: {}>'.format(self._name)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001192
1193 def __getitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001194 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001195 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001196 return self._parser.get(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001197
1198 def __setitem__(self, key, value):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001199 self._parser._validate_value_type(value)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001200 return self._parser.set(self._name, key, value)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001201
1202 def __delitem__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001203 if not self._parser.has_option(self._name, key):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001204 raise KeyError(key)
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001205 return self._parser.remove_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001206
1207 def __contains__(self, key):
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001208 return self._parser.has_option(self._name, key)
Łukasz Langa26d513c2010-11-10 18:57:39 +00001209
1210 def __len__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001211 # XXX weak performance
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001212 return len(self._parser.options(self._name))
Łukasz Langa26d513c2010-11-10 18:57:39 +00001213
1214 def __iter__(self):
Łukasz Langa26d513c2010-11-10 18:57:39 +00001215 # XXX weak performance
1216 # XXX does not break when underlying container state changed
Łukasz Langaa73dc9d2010-11-21 13:56:42 +00001217 return self._parser.options(self._name).__iter__()
1218
1219 @property
1220 def parser(self):
1221 # The parser object of the proxy is read-only.
1222 return self._parser
1223
1224 @property
1225 def name(self):
1226 # The name of the section on a proxy is read-only.
1227 return self._name