dmi parser
[iramuteq] / configparser.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 u"""Configuration file parser.
5
6 A configuration file consists of sections, lead by a "[section]" header,
7 and followed by "name: value" entries, with continuations and such in
8 the style of RFC 822.
9
10 Intrinsic defaults can be specified by passing them into the
11 ConfigParser constructor as a dictionary.
12
13 class:
14
15 ConfigParser -- responsible for parsing a list of
16                     configuration files, and managing the parsed database.
17
18     methods:
19
20     __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
21              delimiters=('=', ':'), comment_prefixes=('#', ';'),
22              inline_comment_prefixes=None, strict=True,
23              empty_lines_in_values=True):
24         Create the parser. When `defaults' is given, it is initialized into the
25         dictionary or intrinsic defaults. The keys must be strings, the values
26         must be appropriate for %()s string interpolation.
27
28         When `dict_type' is given, it will be used to create the dictionary
29         objects for the list of sections, for the options within a section, and
30         for the default values.
31
32         When `delimiters' is given, it will be used as the set of substrings
33         that divide keys from values.
34
35         When `comment_prefixes' is given, it will be used as the set of
36         substrings that prefix comments in empty lines. Comments can be
37         indented.
38
39         When `inline_comment_prefixes' is given, it will be used as the set of
40         substrings that prefix comments in non-empty lines.
41
42         When `strict` is True, the parser won't allow for any section or option
43         duplicates while reading from a single source (file, string or
44         dictionary). Default is True.
45
46         When `empty_lines_in_values' is False (default: True), each empty line
47         marks the end of an option. Otherwise, internal empty lines of
48         a multiline option are kept as part of the value.
49
50         When `allow_no_value' is True (default: False), options without
51         values are accepted; the value presented for these is None.
52
53     sections()
54         Return all the configuration section names, sans DEFAULT.
55
56     has_section(section)
57         Return whether the given section exists.
58
59     has_option(section, option)
60         Return whether the given option exists in the given section.
61
62     options(section)
63         Return list of configuration options for the named section.
64
65     read(filenames, encoding=None)
66         Read and parse the list of named configuration files, given by
67         name.  A single filename is also allowed.  Non-existing files
68         are ignored.  Return list of successfully read files.
69
70     read_file(f, filename=None)
71         Read and parse one configuration file, given as a file object.
72         The filename defaults to f.name; it is only used in error
73         messages (if f has no `name' attribute, the string `<???>' is used).
74
75     read_string(string)
76         Read configuration from a given string.
77
78     read_dict(dictionary)
79         Read configuration from a dictionary. Keys are section names,
80         values are dictionaries with keys and values that should be present
81         in the section. If the used dictionary type preserves order, sections
82         and their keys will be added in order. Values are automatically
83         converted to strings.
84
85     get(section, option, raw=False, vars=None, fallback=_UNSET)
86         Return a string value for the named option.  All % interpolations are
87         expanded in the return values, based on the defaults passed into the
88         constructor and the DEFAULT section.  Additional substitutions may be
89         provided using the `vars' argument, which must be a dictionary whose
90         contents override any pre-existing defaults. If `option' is a key in
91         `vars', the value from `vars' is used.
92
93     getint(section, options, raw=False, vars=None, fallback=_UNSET)
94         Like get(), but convert value to an integer.
95
96     getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
97         Like get(), but convert value to a float.
98
99     getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
100         Like get(), but convert value to a boolean (currently case
101         insensitively defined as 0, false, no, off for False, and 1, true,
102         yes, on for True).  Returns False or True.
103
104     items(section=_UNSET, raw=False, vars=None)
105         If section is given, return a list of tuples with (section_name,
106         section_proxy) for each section, including DEFAULTSECT. Otherwise,
107         return a list of tuples with (name, value) for each option
108         in the section.
109
110     remove_section(section)
111         Remove the given file section and all its options.
112
113     remove_option(section, option)
114         Remove the given option from the given section.
115
116     set(section, option, value)
117         Set the given option.
118
119     write(fp, space_around_delimiters=True)
120         Write the configuration state in .ini format. If
121         `space_around_delimiters' is True (the default), delimiters
122         between keys and values are surrounded by spaces.
123 """
124
125 from __future__ import with_statement
126 from collections import MutableMapping
127 from io import open
128 try:
129     from collections import OrderedDict as _default_dict
130 except ImportError:
131     from ordereddict import OrderedDict as _default_dict
132 import functools
133 import io
134 import itertools
135 import re
136 import sys
137 import warnings
138
139 from configparser_helpers import _ChainMap
140
141 __all__ = [u"NoSectionError", u"DuplicateOptionError", u"DuplicateSectionError",
142            u"NoOptionError", u"InterpolationError", u"InterpolationDepthError",
143            u"InterpolationSyntaxError", u"ParsingError",
144            u"MissingSectionHeaderError",
145            u"ConfigParser", u"SafeConfigParser", u"RawConfigParser",
146            u"DEFAULTSECT", u"MAX_INTERPOLATION_DEPTH"]
147
148 DEFAULTSECT = u"DEFAULT"
149
150 MAX_INTERPOLATION_DEPTH = 10
151
152
153
154 # exception classes
155 class Error(Exception):
156     u"""Base class for ConfigParser exceptions."""
157
158     def _get_message(self):
159         u"""Getter for 'message'; needed only to override deprecation in
160         BaseException.
161         """
162         return self.__message
163
164     def _set_message(self, value):
165         u"""Setter for 'message'; needed only to override deprecation in
166         BaseException.
167         """
168         self.__message = value
169
170     # BaseException.message has been deprecated since Python 2.6.  To prevent
171     # DeprecationWarning from popping up over this pre-existing attribute, use
172     # a new property that takes lookup precedence.
173     message = property(_get_message, _set_message)
174
175     def __init__(self, msg=u''):
176         self.message = msg
177         Exception.__init__(self, msg)
178
179     def __repr__(self):
180         return self.message
181
182     __str__ = __repr__
183
184
185 class NoSectionError(Error):
186     u"""Raised when no section matches a requested option."""
187
188     def __init__(self, section):
189         Error.__init__(self, u'No section: %r' % (section,))
190         self.section = section
191         self.args = (section, )
192
193
194 class DuplicateSectionError(Error):
195     u"""Raised when a section is repeated in an input source.
196
197     Possible repetitions that raise this exception are: multiple creation
198     using the API or in strict parsers when a section is found more than once
199     in a single input file, string or dictionary.
200     """
201
202     def __init__(self, section, source=None, lineno=None):
203         msg = [repr(section), u" already exists"]
204         if source is not None:
205             message = [u"While reading from ", source]
206             if lineno is not None:
207                 message.append(u" [line {0:2d}]".format(lineno))
208             message.append(u": section ")
209             message.extend(msg)
210             msg = message
211         else:
212             msg.insert(0, u"Section ")
213         Error.__init__(self, u"".join(msg))
214         self.section = section
215         self.source = source
216         self.lineno = lineno
217         self.args = (section, source, lineno)
218
219
220 class DuplicateOptionError(Error):
221     u"""Raised by strict parsers when an option is repeated in an input source.
222
223     Current implementation raises this exception only when an option is found
224     more than once in a single file, string or dictionary.
225     """
226
227     def __init__(self, section, option, source=None, lineno=None):
228         msg = [repr(option), u" in section ", repr(section),
229                u" already exists"]
230         if source is not None:
231             message = [u"While reading from ", source]
232             if lineno is not None:
233                 message.append(u" [line {0:2d}]".format(lineno))
234             message.append(u": option ")
235             message.extend(msg)
236             msg = message
237         else:
238             msg.insert(0, u"Option ")
239         Error.__init__(self, u"".join(msg))
240         self.section = section
241         self.option = option
242         self.source = source
243         self.lineno = lineno
244         self.args = (section, option, source, lineno)
245
246
247 class NoOptionError(Error):
248     u"""A requested option was not found."""
249
250     def __init__(self, option, section):
251         Error.__init__(self, u"No option %r in section: %r" %
252                        (option, section))
253         self.option = option
254         self.section = section
255         self.args = (option, section)
256
257
258 class InterpolationError(Error):
259     u"""Base class for interpolation-related exceptions."""
260
261     def __init__(self, option, section, msg):
262         Error.__init__(self, msg)
263         self.option = option
264         self.section = section
265         self.args = (option, section, msg)
266
267
268 class InterpolationMissingOptionError(InterpolationError):
269     u"""A string substitution required a setting which was not available."""
270
271     def __init__(self, option, section, rawval, reference):
272         msg = (u"Bad value substitution:\n"
273                u"\tsection: [%s]\n"
274                u"\toption : %s\n"
275                u"\tkey    : %s\n"
276                u"\trawval : %s\n"
277                % (section, option, reference, rawval))
278         InterpolationError.__init__(self, option, section, msg)
279         self.reference = reference
280         self.args = (option, section, rawval, reference)
281
282
283 class InterpolationSyntaxError(InterpolationError):
284     u"""Raised when the source text contains invalid syntax.
285
286     Current implementation raises this exception when the source text into
287     which substitutions are made does not conform to the required syntax.
288     """
289
290
291 class InterpolationDepthError(InterpolationError):
292     u"""Raised when substitutions are nested too deeply."""
293
294     def __init__(self, option, section, rawval):
295         msg = (u"Value interpolation too deeply recursive:\n"
296                u"\tsection: [%s]\n"
297                u"\toption : %s\n"
298                u"\trawval : %s\n"
299                % (section, option, rawval))
300         InterpolationError.__init__(self, option, section, msg)
301         self.args = (option, section, rawval)
302
303
304 class ParsingError(Error):
305     u"""Raised when a configuration file does not follow legal syntax."""
306
307     def __init__(self, source=None, filename=None):
308         # Exactly one of `source'/`filename' arguments has to be given.
309         # `filename' kept for compatibility.
310         if filename and source:
311             raise ValueError(u"Cannot specify both `filename' and `source'. "
312                              u"Use `source'.")
313         elif not filename and not source:
314             raise ValueError(u"Required argument `source' not given.")
315         elif filename:
316             source = filename
317         Error.__init__(self, u'Source contains parsing errors: %s' % source)
318         self.source = source
319         self.errors = []
320         self.args = (source, )
321
322     @property
323     def filename(self):
324         u"""Deprecated, use `source'."""
325         warnings.warn(
326             u"The 'filename' attribute will be removed in future versions.  "
327             u"Use 'source' instead.",
328             DeprecationWarning, stacklevel=2
329         )
330         return self.source
331
332     @filename.setter
333     def filename(self, value):
334         u"""Deprecated, user `source'."""
335         warnings.warn(
336             u"The 'filename' attribute will be removed in future versions.  "
337             u"Use 'source' instead.",
338             DeprecationWarning, stacklevel=2
339         )
340         self.source = value
341
342     def append(self, lineno, line):
343         self.errors.append((lineno, line))
344         self.message += u'\n\t[line %2d]: %s' % (lineno, line)
345
346
347 class MissingSectionHeaderError(ParsingError):
348     u"""Raised when a key-value pair is found before any section header."""
349
350     def __init__(self, filename, lineno, line):
351         Error.__init__(
352             self,
353             u'File contains no section headers.\nfile: %s, line: %d\n%r' %
354             (filename, lineno, line))
355         self.source = filename
356         self.lineno = lineno
357         self.line = line
358         self.args = (filename, lineno, line)
359
360
361 # Used in parser getters to indicate the default behaviour when a specific
362 # option is not found it to raise an exception. Created to enable `None' as
363 # a valid fallback value.
364 _UNSET = object()
365
366
367 class Interpolation(object):
368     u"""Dummy interpolation that passes the value through with no changes."""
369
370     def before_get(self, parser, section, option, value, defaults):
371         return value
372
373     def before_set(self, parser, section, option, value):
374         return value
375
376     def before_read(self, parser, section, option, value):
377         return value
378
379     def before_write(self, parser, section, option, value):
380         return value
381
382
383 class BasicInterpolation(Interpolation):
384     u"""Interpolation as implemented in the classic ConfigParser.
385
386     The option values can contain format strings which refer to other values in
387     the same section, or values in the special default section.
388
389     For example:
390
391         something: %(dir)s/whatever
392
393     would resolve the "%(dir)s" to the value of dir.  All reference
394     expansions are done late, on demand. If a user needs to use a bare % in
395     a configuration file, she can escape it by writing %%. Other other % usage
396     is considered a user error and raises `InterpolationSyntaxError'."""
397
398     _KEYCRE = re.compile(ur"%\(([^)]+)\)s")
399
400     def before_get(self, parser, section, option, value, defaults):
401         L = []
402         self._interpolate_some(parser, option, L, value, section, defaults, 1)
403         return u''.join(L)
404
405     def before_set(self, parser, section, option, value):
406         tmp_value = value.replace(u'%%', u'') # escaped percent signs
407         tmp_value = self._KEYCRE.sub(u'', tmp_value) # valid syntax
408         if u'%' in tmp_value:
409             raise ValueError(u"invalid interpolation syntax in %r at "
410                              u"position %d" % (value, tmp_value.find(u'%')))
411         return value
412
413     def _interpolate_some(self, parser, option, accum, rest, section, map,
414                           depth):
415         if depth > MAX_INTERPOLATION_DEPTH:
416             raise InterpolationDepthError(option, section, rest)
417         while rest:
418             p = rest.find(u"%")
419             if p < 0:
420                 accum.append(rest)
421                 return
422             if p > 0:
423                 accum.append(rest[:p])
424                 rest = rest[p:]
425             # p is no longer used
426             c = rest[1:2]
427             if c == u"%":
428                 accum.append(u"%")
429                 rest = rest[2:]
430             elif c == u"(":
431                 m = self._KEYCRE.match(rest)
432                 if m is None:
433                     raise InterpolationSyntaxError(option, section,
434                         u"bad interpolation variable reference %r" % rest)
435                 var = parser.optionxform(m.group(1))
436                 rest = rest[m.end():]
437                 try:
438                     v = map[var]
439                 except KeyError:
440                     raise InterpolationMissingOptionError(
441                         option, section, rest, var)
442                 if u"%" in v:
443                     self._interpolate_some(parser, option, accum, v,
444                                            section, map, depth + 1)
445                 else:
446                     accum.append(v)
447             else:
448                 raise InterpolationSyntaxError(
449                     option, section,
450                     u"'%%' must be followed by '%%' or '(', "
451                     u"found: %r" % (rest,))
452
453
454 class ExtendedInterpolation(Interpolation):
455     u"""Advanced variant of interpolation, supports the syntax used by
456     `zc.buildout'. Enables interpolation between sections."""
457
458     _KEYCRE = re.compile(ur"\$\{([^}]+)\}")
459
460     def before_get(self, parser, section, option, value, defaults):
461         L = []
462         self._interpolate_some(parser, option, L, value, section, defaults, 1)
463         return u''.join(L)
464
465     def before_set(self, parser, section, option, value):
466         tmp_value = value.replace(u'$$', u'') # escaped dollar signs
467         tmp_value = self._KEYCRE.sub(u'', tmp_value) # valid syntax
468         if u'$' in tmp_value:
469             raise ValueError(u"invalid interpolation syntax in %r at "
470                              u"position %d" % (value, tmp_value.find(u'%')))
471         return value
472
473     def _interpolate_some(self, parser, option, accum, rest, section, map,
474                           depth):
475         if depth > MAX_INTERPOLATION_DEPTH:
476             raise InterpolationDepthError(option, section, rest)
477         while rest:
478             p = rest.find(u"$")
479             if p < 0:
480                 accum.append(rest)
481                 return
482             if p > 0:
483                 accum.append(rest[:p])
484                 rest = rest[p:]
485             # p is no longer used
486             c = rest[1:2]
487             if c == u"$":
488                 accum.append(u"$")
489                 rest = rest[2:]
490             elif c == u"{":
491                 m = self._KEYCRE.match(rest)
492                 if m is None:
493                     raise InterpolationSyntaxError(option, section,
494                         u"bad interpolation variable reference %r" % rest)
495                 path = m.group(1).split(u':')
496                 rest = rest[m.end():]
497                 sect = section
498                 opt = option
499                 try:
500                     if len(path) == 1:
501                         opt = parser.optionxform(path[0])
502                         v = map[opt]
503                     elif len(path) == 2:
504                         sect = path[0]
505                         opt = parser.optionxform(path[1])
506                         v = parser.get(sect, opt, raw=True)
507                     else:
508                         raise InterpolationSyntaxError(
509                             option, section,
510                             u"More than one ':' found: %r" % (rest,))
511                 except (KeyError, NoSectionError, NoOptionError):
512                     raise InterpolationMissingOptionError(
513                         option, section, rest, u":".join(path))
514                 if u"$" in v:
515                     self._interpolate_some(parser, opt, accum, v, sect,
516                                            dict(parser.items(sect, raw=True)),
517                                            depth + 1)
518                 else:
519                     accum.append(v)
520             else:
521                 raise InterpolationSyntaxError(
522                     option, section,
523                     u"'$' must be followed by '$' or '{', "
524                     u"found: %r" % (rest,))
525
526
527 class LegacyInterpolation(Interpolation):
528     u"""Deprecated interpolation used in old versions of ConfigParser.
529     Use BasicInterpolation or ExtendedInterpolation instead."""
530
531     _KEYCRE = re.compile(ur"%\(([^)]*)\)s|.")
532
533     def before_get(self, parser, section, option, value, vars):
534         rawval = value
535         depth = MAX_INTERPOLATION_DEPTH
536         while depth:                    # Loop through this until it's done
537             depth -= 1
538             if value and u"%(" in value:
539                 replace = functools.partial(self._interpolation_replace,
540                                             parser=parser)
541                 value = self._KEYCRE.sub(replace, value)
542                 try:
543                     value = value % vars
544                 except KeyError, e:
545                     raise InterpolationMissingOptionError(
546                         option, section, rawval, e.args[0])
547             else:
548                 break
549         if value and u"%(" in value:
550             raise InterpolationDepthError(option, section, rawval)
551         return value
552
553     def before_set(self, parser, section, option, value):
554         return value
555
556     @staticmethod
557     def _interpolation_replace(match, parser):
558         s = match.group(1)
559         if s is None:
560             return match.group()
561         else:
562             return u"%%(%s)s" % parser.optionxform(s)
563
564
565 class RawConfigParser(MutableMapping):
566     u"""ConfigParser that does not do interpolation."""
567
568     # Regular expressions for parsing section headers and options
569     _SECT_TMPL = ur"""
570         \[                                 # [
571         (?P<header>[^]]+)                  # very permissive!
572         \]                                 # ]
573         """
574     _OPT_TMPL = ur"""
575         (?P<option>.*?)                    # very permissive!
576         \s*(?P<vi>{delim})\s*              # any number of space/tab,
577                                            # followed by any of the
578                                            # allowed delimiters,
579                                            # followed by any space/tab
580         (?P<value>.*)$                     # everything up to eol
581         """
582     _OPT_NV_TMPL = ur"""
583         (?P<option>.*?)                    # very permissive!
584         \s*(?:                             # any number of space/tab,
585         (?P<vi>{delim})\s*                 # optionally followed by
586                                            # any of the allowed
587                                            # delimiters, followed by any
588                                            # space/tab
589         (?P<value>.*))?$                   # everything up to eol
590         """
591     # Interpolation algorithm to be used if the user does not specify another
592     _DEFAULT_INTERPOLATION = Interpolation()
593     # Compiled regular expression for matching sections
594     SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
595     # Compiled regular expression for matching options with typical separators
596     OPTCRE = re.compile(_OPT_TMPL.format(delim=u"=|:"), re.VERBOSE)
597     # Compiled regular expression for matching options with optional values
598     # delimited using typical separators
599     OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim=u"=|:"), re.VERBOSE)
600     # Compiled regular expression for matching leading whitespace in a line
601     NONSPACECRE = re.compile(ur"\S")
602     # Possible boolean values in the configuration.
603     BOOLEAN_STATES = {u'1': True, u'yes': True, u'true': True, u'on': True,
604                       u'0': False, u'no': False, u'false': False, u'off': False}
605
606     def __init__(self, defaults=None, dict_type=_default_dict,
607                  allow_no_value=False, **_3to2kwargs):
608
609         if 'interpolation' in _3to2kwargs: interpolation = _3to2kwargs['interpolation']; del _3to2kwargs['interpolation']
610         else: interpolation = _UNSET
611         if 'default_section' in _3to2kwargs: default_section = _3to2kwargs['default_section']; del _3to2kwargs['default_section']
612         else: default_section = DEFAULTSECT
613         if 'empty_lines_in_values' in _3to2kwargs: empty_lines_in_values = _3to2kwargs['empty_lines_in_values']; del _3to2kwargs['empty_lines_in_values']
614         else: empty_lines_in_values = True
615         if 'strict' in _3to2kwargs: strict = _3to2kwargs['strict']; del _3to2kwargs['strict']
616         else: strict = True
617         if 'inline_comment_prefixes' in _3to2kwargs: inline_comment_prefixes = _3to2kwargs['inline_comment_prefixes']; del _3to2kwargs['inline_comment_prefixes']
618         else: inline_comment_prefixes = None
619         if 'comment_prefixes' in _3to2kwargs: comment_prefixes = _3to2kwargs['comment_prefixes']; del _3to2kwargs['comment_prefixes']
620         else: comment_prefixes = (u'#', u';')
621         if 'delimiters' in _3to2kwargs: delimiters = _3to2kwargs['delimiters']; del _3to2kwargs['delimiters']
622         else: delimiters = (u'=', u':')
623         self._dict = dict_type
624         self._sections = self._dict()
625         self._defaults = self._dict()
626         self._proxies = self._dict()
627         self._proxies[default_section] = SectionProxy(self, default_section)
628         if defaults:
629             for key, value in defaults.items():
630                 self._defaults[self.optionxform(key)] = value
631         self._delimiters = tuple(delimiters)
632         if delimiters == (u'=', u':'):
633             self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
634         else:
635             d = u"|".join(re.escape(d) for d in delimiters)
636             if allow_no_value:
637                 self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
638                                           re.VERBOSE)
639             else:
640                 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
641                                           re.VERBOSE)
642         self._comment_prefixes = tuple(comment_prefixes or ())
643         self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
644         self._strict = strict
645         self._allow_no_value = allow_no_value
646         self._empty_lines_in_values = empty_lines_in_values
647         self.default_section=default_section
648         self._interpolation = interpolation
649         if self._interpolation is _UNSET:
650             self._interpolation = self._DEFAULT_INTERPOLATION
651         if self._interpolation is None:
652             self._interpolation = Interpolation()
653
654     def defaults(self):
655         return self._defaults
656
657     def sections(self):
658         u"""Return a list of section names, excluding [DEFAULT]"""
659         # self._sections will never have [DEFAULT] in it
660         return list(self._sections.keys())
661
662     def add_section(self, section):
663         u"""Create a new section in the configuration.
664
665         Raise DuplicateSectionError if a section by the specified name
666         already exists. Raise ValueError if name is DEFAULT.
667         """
668         if section == self.default_section:
669             raise ValueError(u'Invalid section name: %r' % section)
670
671         if section in self._sections:
672             raise DuplicateSectionError(section)
673         self._sections[section] = self._dict()
674         self._proxies[section] = SectionProxy(self, section)
675
676     def has_section(self, section):
677         u"""Indicate whether the named section is present in the configuration.
678
679         The DEFAULT section is not acknowledged.
680         """
681         return section in self._sections
682
683     def options(self, section):
684         u"""Return a list of option names for the given section name."""
685         try:
686             opts = self._sections[section].copy()
687         except KeyError:
688             raise NoSectionError(section)
689         opts.update(self._defaults)
690         return list(opts.keys())
691
692     def read(self, filenames, encoding=None):
693         u"""Read and parse a filename or a list of filenames.
694
695         Files that cannot be opened are silently ignored; this is
696         designed so that you can specify a list of potential
697         configuration file locations (e.g. current directory, user's
698         home directory, systemwide directory), and all existing
699         configuration files in the list will be read.  A single
700         filename may also be given.
701
702         Return list of successfully read files.
703         """
704         if isinstance(filenames, unicode):
705             filenames = [filenames]
706         read_ok = []
707         for filename in filenames:
708             try:
709                 with open(filename, encoding=encoding) as fp:
710                     self._read(fp, filename)
711             except IOError:
712                 continue
713             read_ok.append(filename)
714         return read_ok
715
716     def read_file(self, f, source=None):
717         u"""Like read() but the argument must be a file-like object.
718
719         The `f' argument must be iterable, returning one line at a time.
720         Optional second argument is the `source' specifying the name of the
721         file being read. If not given, it is taken from f.name. If `f' has no
722         `name' attribute, `<???>' is used.
723         """
724         if source is None:
725             try:
726                 source = f.name
727             except AttributeError:
728                 source = u'<???>'
729         self._read(f, source)
730
731     def read_string(self, string, source=u'<string>'):
732         u"""Read configuration from a given string."""
733         sfile = io.StringIO(string)
734         self.read_file(sfile, source)
735
736     def read_dict(self, dictionary, source=u'<dict>'):
737         u"""Read configuration from a dictionary.
738
739         Keys are section names, values are dictionaries with keys and values
740         that should be present in the section. If the used dictionary type
741         preserves order, sections and their keys will be added in order.
742
743         All types held in the dictionary are converted to strings during
744         reading, including section names, option names and keys.
745
746         Optional second argument is the `source' specifying the name of the
747         dictionary being read.
748         """
749         elements_added = set()
750         for section, keys in dictionary.items():
751             section = unicode(section)
752             try:
753                 self.add_section(section)
754             except (DuplicateSectionError, ValueError):
755                 if self._strict and section in elements_added:
756                     raise
757             elements_added.add(section)
758             for key, value in keys.items():
759                 key = self.optionxform(unicode(key))
760                 if value is not None:
761                     value = unicode(value)
762                 if self._strict and (section, key) in elements_added:
763                     raise DuplicateOptionError(section, key, source)
764                 elements_added.add((section, key))
765                 self.set(section, key, value)
766
767     def readfp(self, fp, filename=None):
768         u"""Deprecated, use read_file instead."""
769         warnings.warn(
770             u"This method will be removed in future versions.  "
771             u"Use 'parser.read_file()' instead.",
772             DeprecationWarning, stacklevel=2
773         )
774         self.read_file(fp, source=filename)
775
776     def get(self, section, option, **_3to2kwargs):
777         if 'fallback' in _3to2kwargs: fallback = _3to2kwargs['fallback']; del _3to2kwargs['fallback']
778         else: fallback = _UNSET
779         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
780         else: vars = None
781         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
782         else: raw = False
783         u"""Get an option value for a given section.
784
785         If `vars' is provided, it must be a dictionary. The option is looked up
786         in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
787         If the key is not found and `fallback' is provided, it is used as
788         a fallback value. `None' can be provided as a `fallback' value.
789
790         If interpolation is enabled and the optional argument `raw' is False,
791         all interpolations are expanded in the return values.
792
793         Arguments `raw', `vars', and `fallback' are keyword only.
794
795         The section DEFAULT is special.
796         """
797         try:
798             d = self._unify_values(section, vars)
799         except NoSectionError:
800             if fallback is _UNSET:
801                 raise
802             else:
803                 return fallback
804         option = self.optionxform(option)
805         try:
806             value = d[option]
807         except KeyError:
808             if fallback is _UNSET:
809                 raise NoOptionError(option, section)
810             else:
811                 return fallback
812
813         if raw or value is None:
814             return value
815         else:
816             return self._interpolation.before_get(self, section, option, value,
817                                                   d)
818
819     def _get(self, section, conv, option, **kwargs):
820         return conv(self.get(section, option, **kwargs))
821
822     def getint(self, section, option, **_3to2kwargs):
823         if 'fallback' in _3to2kwargs: fallback = _3to2kwargs['fallback']; del _3to2kwargs['fallback']
824         else: fallback = _UNSET
825         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
826         else: vars = None
827         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
828         else: raw = False
829         try:
830             return self._get(section, int, option, raw=raw, vars=vars)
831         except (NoSectionError, NoOptionError):
832             if fallback is _UNSET:
833                 raise
834             else:
835                 return fallback
836
837     def getfloat(self, section, option, **_3to2kwargs):
838         if 'fallback' in _3to2kwargs: fallback = _3to2kwargs['fallback']; del _3to2kwargs['fallback']
839         else: fallback = _UNSET
840         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
841         else: vars = None
842         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
843         else: raw = False
844         try:
845             return self._get(section, float, option, raw=raw, vars=vars)
846         except (NoSectionError, NoOptionError):
847             if fallback is _UNSET:
848                 raise
849             else:
850                 return fallback
851
852     def getboolean(self, section, option, **_3to2kwargs):
853         if 'fallback' in _3to2kwargs: fallback = _3to2kwargs['fallback']; del _3to2kwargs['fallback']
854         else: fallback = _UNSET
855         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
856         else: vars = None
857         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
858         else: raw = False
859         try:
860             return self._get(section, self._convert_to_boolean, option,
861                              raw=raw, vars=vars)
862         except (NoSectionError, NoOptionError):
863             if fallback is _UNSET:
864                 raise
865             else:
866                 return fallback
867
868     def items(self, section=_UNSET, raw=False, vars=None):
869         u"""Return a list of (name, value) tuples for each option in a section.
870
871         All % interpolations are expanded in the return values, based on the
872         defaults passed into the constructor, unless the optional argument
873         `raw' is true.  Additional substitutions may be provided using the
874         `vars' argument, which must be a dictionary whose contents overrides
875         any pre-existing defaults.
876
877         The section DEFAULT is special.
878         """
879         if section is _UNSET:
880             return super(RawConfigParser, self).items()
881         d = self._defaults.copy()
882         try:
883             d.update(self._sections[section])
884         except KeyError:
885             if section != self.default_section:
886                 raise NoSectionError(section)
887         # Update with the entry specific variables
888         if vars:
889             for key, value in vars.items():
890                 d[self.optionxform(key)] = value
891         value_getter = lambda option: self._interpolation.before_get(self,
892             section, option, d[option], d)
893         if raw:
894             value_getter = lambda option: d[option]
895         return [(option, value_getter(option)) for option in d.keys()]
896
897     def optionxform(self, optionstr):
898         return optionstr.lower()
899
900     def has_option(self, section, option):
901         u"""Check for the existence of a given option in a given section.
902         If the specified `section' is None or an empty string, DEFAULT is
903         assumed. If the specified `section' does not exist, returns False."""
904         if not section or section == self.default_section:
905             option = self.optionxform(option)
906             return option in self._defaults
907         elif section not in self._sections:
908             return False
909         else:
910             option = self.optionxform(option)
911             return (option in self._sections[section]
912                     or option in self._defaults)
913
914     def set(self, section, option, value=None):
915         u"""Set an option."""
916         if value:
917             value = self._interpolation.before_set(self, section, option,
918                                                    value)
919         if not section or section == self.default_section:
920             sectdict = self._defaults
921         else:
922             try:
923                 sectdict = self._sections[section]
924             except KeyError:
925                 raise NoSectionError(section)
926         sectdict[self.optionxform(option)] = value
927
928     def write(self, fp, space_around_delimiters=True):
929         u"""Write an .ini-format representation of the configuration state.
930
931         If `space_around_delimiters' is True (the default), delimiters
932         between keys and values are surrounded by spaces.
933         """
934         if space_around_delimiters:
935             d = u" {0} ".format(self._delimiters[0])
936         else:
937             d = self._delimiters[0]
938         if self._defaults:
939             self._write_section(fp, self.default_section,
940                                     self._defaults.items(), d)
941         for section in self._sections:
942             self._write_section(fp, section,
943                                 self._sections[section].items(), d)
944
945     def _write_section(self, fp, section_name, section_items, delimiter):
946         u"""Write a single section to the specified `fp'."""
947         fp.write(u"[{0}]\n".format(section_name))
948         for key, value in section_items:
949             value = self._interpolation.before_write(self, section_name, key,
950                                                      value)
951             if value is not None or not self._allow_no_value:
952                 value = delimiter + unicode(value).replace(u'\n', u'\n\t')
953             else:
954                 value = u""
955             fp.write(u"{0}{1}\n".format(key, value))
956         fp.write(u"\n")
957
958     def remove_option(self, section, option):
959         u"""Remove an option."""
960         if not section or section == self.default_section:
961             sectdict = self._defaults
962         else:
963             try:
964                 sectdict = self._sections[section]
965             except KeyError:
966                 raise NoSectionError(section)
967         option = self.optionxform(option)
968         existed = option in sectdict
969         if existed:
970             del sectdict[option]
971         return existed
972
973     def remove_section(self, section):
974         u"""Remove a file section."""
975         existed = section in self._sections
976         if existed:
977             del self._sections[section]
978             del self._proxies[section]
979         return existed
980
981     def __getitem__(self, key):
982         if key != self.default_section and not self.has_section(key):
983             raise KeyError(key)
984         return self._proxies[key]
985
986     def __setitem__(self, key, value):
987         # To conform with the mapping protocol, overwrites existing values in
988         # the section.
989
990         # XXX this is not atomic if read_dict fails at any point. Then again,
991         # no update method in configparser is atomic in this implementation.
992         self.remove_section(key)
993         self.read_dict({key: value})
994
995     def __delitem__(self, key):
996         if key == self.default_section:
997             raise ValueError(u"Cannot remove the default section.")
998         if not self.has_section(key):
999             raise KeyError(key)
1000         self.remove_section(key)
1001
1002     def __contains__(self, key):
1003         return key == self.default_section or self.has_section(key)
1004
1005     def __len__(self):
1006         return len(self._sections) + 1 # the default section
1007
1008     def __iter__(self):
1009         # XXX does it break when underlying container state changed?
1010         return itertools.chain((self.default_section,), self._sections.keys())
1011
1012     def _read(self, fp, fpname):
1013         u"""Parse a sectioned configuration file.
1014
1015         Each section in a configuration file contains a header, indicated by
1016         a name in square brackets (`[]'), plus key/value options, indicated by
1017         `name' and `value' delimited with a specific substring (`=' or `:' by
1018         default).
1019
1020         Values can span multiple lines, as long as they are indented deeper
1021         than the first line of the value. Depending on the parser's mode, blank
1022         lines may be treated as parts of multiline values or ignored.
1023
1024         Configuration files may include comments, prefixed by specific
1025         characters (`#' and `;' by default). Comments may appear on their own
1026         in an otherwise empty line or may be entered in lines holding values or
1027         section names.
1028         """
1029         elements_added = set()
1030         cursect = None                        # None, or a dictionary
1031         sectname = None
1032         optname = None
1033         lineno = 0
1034         indent_level = 0
1035         e = None                              # None, or an exception
1036         for lineno, line in enumerate(fp, start=1):
1037             comment_start = None
1038             # strip inline comments
1039             for prefix in self._inline_comment_prefixes:
1040                 index = line.find(prefix)
1041                 if index == 0 or (index > 0 and line[index-1].isspace()):
1042                     comment_start = index
1043                     break
1044             # strip full line comments
1045             for prefix in self._comment_prefixes:
1046                 if line.strip().startswith(prefix):
1047                     comment_start = 0
1048                     break
1049             value = line[:comment_start].strip()
1050             if not value:
1051                 if self._empty_lines_in_values:
1052                     # add empty line to the value, but only if there was no
1053                     # comment on the line
1054                     if (comment_start is None and
1055                         cursect is not None and
1056                         optname and
1057                         cursect[optname] is not None):
1058                         cursect[optname].append(u'') # newlines added at join
1059                 else:
1060                     # empty line marks end of value
1061                     indent_level = sys.maxsize
1062                 continue
1063             # continuation line?
1064             first_nonspace = self.NONSPACECRE.search(line)
1065             cur_indent_level = first_nonspace.start() if first_nonspace else 0
1066             if (cursect is not None and optname and
1067                 cur_indent_level > indent_level):
1068                 cursect[optname].append(value)
1069             # a section header or option header?
1070             else:
1071                 indent_level = cur_indent_level
1072                 # is it a section header?
1073                 mo = self.SECTCRE.match(value)
1074                 if mo:
1075                     sectname = mo.group(u'header')
1076                     if sectname in self._sections:
1077                         if self._strict and sectname in elements_added:
1078                             raise DuplicateSectionError(sectname, fpname,
1079                                                         lineno)
1080                         cursect = self._sections[sectname]
1081                         elements_added.add(sectname)
1082                     elif sectname == self.default_section:
1083                         cursect = self._defaults
1084                     else:
1085                         cursect = self._dict()
1086                         self._sections[sectname] = cursect
1087                         self._proxies[sectname] = SectionProxy(self, sectname)
1088                         elements_added.add(sectname)
1089                     # So sections can't start with a continuation line
1090                     optname = None
1091                 # no section header in the file?
1092                 elif cursect is None:
1093                     raise MissingSectionHeaderError(fpname, lineno, line)
1094                 # an option line?
1095                 else:
1096                     mo = self._optcre.match(value)
1097                     if mo:
1098                         optname, vi, optval = mo.group(u'option', u'vi', u'value')
1099                         if not optname:
1100                             e = self._handle_error(e, fpname, lineno, line)
1101                         optname = self.optionxform(optname.rstrip())
1102                         if (self._strict and
1103                             (sectname, optname) in elements_added):
1104                             raise DuplicateOptionError(sectname, optname,
1105                                                        fpname, lineno)
1106                         elements_added.add((sectname, optname))
1107                         # This check is fine because the OPTCRE cannot
1108                         # match if it would set optval to None
1109                         if optval is not None:
1110                             optval = optval.strip()
1111                             cursect[optname] = [optval]
1112                         else:
1113                             # valueless option handling
1114                             cursect[optname] = None
1115                     else:
1116                         # a non-fatal parsing error occurred. set up the
1117                         # exception but keep going. the exception will be
1118                         # raised at the end of the file and will contain a
1119                         # list of all bogus lines
1120                         e = self._handle_error(e, fpname, lineno, line)
1121         # if any parsing errors occurred, raise an exception
1122         if e:
1123             raise e
1124         self._join_multiline_values()
1125
1126     def _join_multiline_values(self):
1127         defaults = self.default_section, self._defaults
1128         all_sections = itertools.chain((defaults,),
1129                                        self._sections.items())
1130         for section, options in all_sections:
1131             for name, val in options.items():
1132                 if isinstance(val, list):
1133                     val = u'\n'.join(val).rstrip()
1134                 options[name] = self._interpolation.before_read(self,
1135                                                                 section,
1136                                                                 name, val)
1137
1138     def _handle_error(self, exc, fpname, lineno, line):
1139         if not exc:
1140             exc = ParsingError(fpname)
1141         exc.append(lineno, repr(line))
1142         return exc
1143
1144     def _unify_values(self, section, vars):
1145         u"""Create a sequence of lookups with 'vars' taking priority over
1146         the 'section' which takes priority over the DEFAULTSECT.
1147
1148         """
1149         sectiondict = {}
1150         try:
1151             sectiondict = self._sections[section]
1152         except KeyError:
1153             if section != self.default_section:
1154                 raise NoSectionError(section)
1155         # Update with the entry specific variables
1156         vardict = {}
1157         if vars:
1158             for key, value in vars.items():
1159                 if value is not None:
1160                     value = unicode(value)
1161                 vardict[self.optionxform(key)] = value
1162         return _ChainMap(vardict, sectiondict, self._defaults)
1163
1164     def _convert_to_boolean(self, value):
1165         u"""Return a boolean value translating from other types if necessary.
1166         """
1167         if value.lower() not in self.BOOLEAN_STATES:
1168             raise ValueError(u'Not a boolean: %s' % value)
1169         return self.BOOLEAN_STATES[value.lower()]
1170
1171     def _validate_value_types(self, **_3to2kwargs):
1172         if 'value' in _3to2kwargs: value = _3to2kwargs['value']; del _3to2kwargs['value']
1173         else: value = u""
1174         if 'option' in _3to2kwargs: option = _3to2kwargs['option']; del _3to2kwargs['option']
1175         else: option = u""
1176         if 'section' in _3to2kwargs: section = _3to2kwargs['section']; del _3to2kwargs['section']
1177         else: section = u""
1178         u"""Raises a TypeError for non-string values.
1179
1180         The only legal non-string value if we allow valueless
1181         options is None, so we need to check if the value is a
1182         string if:
1183         - we do not allow valueless options, or
1184         - we allow valueless options but the value is not None
1185
1186         For compatibility reasons this method is not used in classic set()
1187         for RawConfigParsers. It is invoked in every case for mapping protocol
1188         access and in ConfigParser.set().
1189         """
1190         if not isinstance(section, basestring):
1191             raise TypeError(u"section names must be strings")
1192         if not isinstance(option, basestring):
1193             raise TypeError(u"option keys must be strings")
1194         if not self._allow_no_value or value:
1195             if not isinstance(value, basestring):
1196                 raise TypeError(u"option values must be strings")
1197         return (unicode(section), unicode(option), (value if value is None
1198             else unicode(value)))
1199
1200
1201 class ConfigParser(RawConfigParser):
1202     u"""ConfigParser implementing interpolation."""
1203
1204     _DEFAULT_INTERPOLATION = BasicInterpolation()
1205
1206     def set(self, section, option, value=None):
1207         u"""Set an option.  Extends RawConfigParser.set by validating type and
1208         interpolation syntax on the value."""
1209         _, option, value = self._validate_value_types(option=option, value=value)
1210         super(ConfigParser, self).set(section, option, value)
1211
1212     def add_section(self, section):
1213         u"""Create a new section in the configuration.  Extends
1214         RawConfigParser.add_section by validating if the section name is
1215         a string."""
1216         section, _, _ = self._validate_value_types(section=section)
1217         super(ConfigParser, self).add_section(section)
1218
1219
1220 class SafeConfigParser(ConfigParser):
1221     u"""ConfigParser alias for backwards compatibility purposes."""
1222
1223     def __init__(self, *args, **kwargs):
1224         super(SafeConfigParser, self).__init__(*args, **kwargs)
1225         warnings.warn(
1226             u"The SafeConfigParser class has been renamed to ConfigParser "
1227             u"in Python 3.2. This alias will be removed in future versions."
1228             u" Use ConfigParser directly instead.",
1229             DeprecationWarning, stacklevel=2
1230         )
1231
1232
1233 class SectionProxy(MutableMapping):
1234     u"""A proxy for a single section from a parser."""
1235
1236     def __init__(self, parser, name):
1237         u"""Creates a view on a section of the specified `name` in `parser`."""
1238         self._parser = parser
1239         self._name = name
1240
1241     def __repr__(self):
1242         return u'<Section: {0}>'.format(self._name)
1243
1244     def __getitem__(self, key):
1245         if not self._parser.has_option(self._name, key):
1246             raise KeyError(key)
1247         return self._parser.get(self._name, key)
1248
1249     def __setitem__(self, key, value):
1250         _, key, value = self._parser._validate_value_types(option=key, value=value)
1251         return self._parser.set(self._name, key, value)
1252
1253     def __delitem__(self, key):
1254         if not (self._parser.has_option(self._name, key) and
1255                 self._parser.remove_option(self._name, key)):
1256             raise KeyError(key)
1257
1258     def __contains__(self, key):
1259         return self._parser.has_option(self._name, key)
1260
1261     def __len__(self):
1262         return len(self._options())
1263
1264     def __iter__(self):
1265         return self._options().__iter__()
1266
1267     def _options(self):
1268         if self._name != self._parser.default_section:
1269             return self._parser.options(self._name)
1270         else:
1271             return self._parser.defaults()
1272
1273     def get(self, option, fallback=None, **_3to2kwargs):
1274         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
1275         else: vars = None
1276         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
1277         else: raw = False
1278         return self._parser.get(self._name, option, raw=raw, vars=vars,
1279                                 fallback=fallback)
1280
1281     def getint(self, option, fallback=None, **_3to2kwargs):
1282         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
1283         else: vars = None
1284         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
1285         else: raw = False
1286         return self._parser.getint(self._name, option, raw=raw, vars=vars,
1287                                    fallback=fallback)
1288
1289     def getfloat(self, option, fallback=None, **_3to2kwargs):
1290         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
1291         else: vars = None
1292         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
1293         else: raw = False
1294         return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
1295                                      fallback=fallback)
1296
1297     def getboolean(self, option, fallback=None, **_3to2kwargs):
1298         if 'vars' in _3to2kwargs: vars = _3to2kwargs['vars']; del _3to2kwargs['vars']
1299         else: vars = None
1300         if 'raw' in _3to2kwargs: raw = _3to2kwargs['raw']; del _3to2kwargs['raw']
1301         else: raw = False
1302         return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
1303                                        fallback=fallback)
1304
1305     @property
1306     def parser(self):
1307         # The parser object of the proxy is read-only.
1308         return self._parser
1309
1310     @property
1311     def name(self):
1312         # The name of the section on a proxy is read-only.
1313         return self._name