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