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