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