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