Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 1 | :mod:`configparser` --- Configuration file parser |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2 | ================================================= |
| 3 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 4 | .. module:: configparser |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 5 | :synopsis: Configuration file parser. |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 6 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 7 | .. moduleauthor:: Ken Manheimer <klm@zope.com> |
| 8 | .. moduleauthor:: Barry Warsaw <bwarsaw@python.org> |
| 9 | .. moduleauthor:: Eric S. Raymond <esr@thyrsus.com> |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 10 | .. moduleauthor:: Łukasz Langa <lukasz@langa.pl> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | .. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org> |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 12 | .. sectionauthor:: Łukasz Langa <lukasz@langa.pl> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 | .. index:: |
| 15 | pair: .ini; file |
| 16 | pair: configuration; file |
| 17 | single: ini file |
| 18 | single: Windows ini file |
| 19 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 20 | This module provides the :class:`SafeConfigParser` class which implements |
| 21 | a basic configuration language which provides a structure similar to what's |
| 22 | found in Microsoft Windows INI files. You can use this to write Python |
| 23 | programs which can be customized by end users easily. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 24 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 25 | .. note:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 26 | |
Georg Brandl | e720c0a | 2009-04-27 16:20:50 +0000 | [diff] [blame] | 27 | This library does *not* interpret or write the value-type prefixes used in |
| 28 | the Windows Registry extended version of INI syntax. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 29 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 30 | .. seealso:: |
| 31 | |
| 32 | Module :mod:`shlex` |
| 33 | Support for a creating Unix shell-like mini-languages which can be used |
| 34 | as an alternate format for application configuration files. |
| 35 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 36 | Module :mod:`json` |
| 37 | The json module implements a subset of JavaScript syntax which can also |
| 38 | be used for this purpose. |
| 39 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 40 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 41 | Quick Start |
| 42 | ----------- |
| 43 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 44 | Let's take a very basic configuration file that looks like this: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 45 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 46 | .. code-block:: ini |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 47 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 48 | [DEFAULT] |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 49 | ServerAliveInterval = 45 |
| 50 | Compression = yes |
| 51 | CompressionLevel = 9 |
| 52 | ForwardX11 = yes |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 53 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 54 | [bitbucket.org] |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 55 | User = hg |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 56 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 57 | [topsecret.server.com] |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 58 | Port = 50022 |
| 59 | ForwardX11 = no |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 60 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 61 | The structure of INI files is described `in the following section |
| 62 | <#supported-ini-file-structure>`_. Essentially, the file |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 63 | consists of sections, each of which contains keys with values. |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 64 | :mod:`configparser` classes can read and write such files. Let's start by |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 65 | creating the above configuration file programatically. |
| 66 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 67 | .. doctest:: |
| 68 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 69 | >>> import configparser |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 70 | >>> config = configparser.SafeConfigParser() |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 71 | >>> config['DEFAULT'] = {'ServerAliveInterval': '45', |
| 72 | ... 'Compression': 'yes', |
| 73 | ... 'CompressionLevel': '9'} |
| 74 | >>> config['bitbucket.org'] = {} |
| 75 | >>> config['bitbucket.org']['User'] = 'hg' |
| 76 | >>> config['topsecret.server.com'] = {} |
| 77 | >>> topsecret = config['topsecret.server.com'] |
| 78 | >>> topsecret['Port'] = '50022' # mutates the parser |
| 79 | >>> topsecret['ForwardX11'] = 'no' # same here |
| 80 | >>> config['DEFAULT']['ForwardX11'] = 'yes' |
| 81 | >>> with open('example.ini', 'w') as configfile: |
| 82 | ... config.write(configfile) |
| 83 | ... |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 84 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 85 | As you can see, we can treat a config parser much like a dictionary. |
| 86 | There are differences, `outlined later <#mapping-protocol-access>`_, but |
| 87 | the behavior is very close to what you would expect from a dictionary. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 88 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 89 | Now that we have created and saved a configuration file, let's read it |
| 90 | back and explore the data it holds. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 91 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 92 | .. doctest:: |
| 93 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 94 | >>> import configparser |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 95 | >>> config = configparser.SafeConfigParser() |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 96 | >>> config.sections() |
| 97 | [] |
| 98 | >>> config.read('example.ini') |
| 99 | ['example.ini'] |
| 100 | >>> config.sections() |
| 101 | ['bitbucket.org', 'topsecret.server.com'] |
| 102 | >>> 'bitbucket.org' in config |
| 103 | True |
| 104 | >>> 'bytebong.com' in config |
| 105 | False |
| 106 | >>> config['bitbucket.org']['User'] |
| 107 | 'hg' |
| 108 | >>> config['DEFAULT']['Compression'] |
| 109 | 'yes' |
| 110 | >>> topsecret = config['topsecret.server.com'] |
| 111 | >>> topsecret['ForwardX11'] |
| 112 | 'no' |
| 113 | >>> topsecret['Port'] |
| 114 | '50022' |
| 115 | >>> for key in config['bitbucket.org']: print(key) |
| 116 | ... |
| 117 | user |
| 118 | compressionlevel |
| 119 | serveraliveinterval |
| 120 | compression |
| 121 | forwardx11 |
| 122 | >>> config['bitbucket.org']['ForwardX11'] |
| 123 | 'yes' |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 124 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 125 | As we can see above, the API is pretty straightforward. The only bit of magic |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 126 | involves the ``DEFAULT`` section which provides default values for all other |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 127 | sections [1]_. Note also that keys in sections are |
| 128 | case-insensitive and stored in lowercase [1]_. |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 129 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 130 | |
| 131 | Supported Datatypes |
| 132 | ------------------- |
| 133 | |
| 134 | Config parsers do not guess datatypes of values in configuration files, always |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 135 | storing them internally as strings. This means that if you need other |
| 136 | datatypes, you should convert on your own: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 137 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 138 | .. doctest:: |
| 139 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 140 | >>> int(topsecret['Port']) |
| 141 | 50022 |
| 142 | >>> float(topsecret['CompressionLevel']) |
| 143 | 9.0 |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 144 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 145 | Extracting Boolean values is not that simple, though. Passing the value |
| 146 | to ``bool()`` would do no good since ``bool('False')`` is still |
| 147 | ``True``. This is why config parsers also provide :meth:`getboolean`. |
| 148 | This method is case-insensitive and recognizes Boolean values from |
| 149 | ``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [1]_. |
| 150 | For example: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 151 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 152 | .. doctest:: |
| 153 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 154 | >>> topsecret.getboolean('ForwardX11') |
| 155 | False |
| 156 | >>> config['bitbucket.org'].getboolean('ForwardX11') |
| 157 | True |
| 158 | >>> config.getboolean('bitbucket.org', 'Compression') |
| 159 | True |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 160 | |
| 161 | Apart from :meth:`getboolean`, config parsers also provide equivalent |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 162 | :meth:`getint` and :meth:`getfloat` methods, but these are far less |
| 163 | useful since conversion using :func:`int` and :func:`float` is |
| 164 | sufficient for these types. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 165 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 166 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 167 | Fallback Values |
| 168 | --------------- |
| 169 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 170 | As with a dictionary, you can use a section's :meth:`get` method to |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 171 | provide fallback values: |
| 172 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 173 | .. doctest:: |
| 174 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 175 | >>> topsecret.get('Port') |
| 176 | '50022' |
| 177 | >>> topsecret.get('CompressionLevel') |
| 178 | '9' |
| 179 | >>> topsecret.get('Cipher') |
| 180 | >>> topsecret.get('Cipher', '3des-cbc') |
| 181 | '3des-cbc' |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 182 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 183 | Please note that default values have precedence over fallback values. |
| 184 | For instance, in our example the ``'CompressionLevel'`` key was |
| 185 | specified only in the ``'DEFAULT'`` section. If we try to get it from |
| 186 | the section ``'topsecret.server.com'``, we will always get the default, |
| 187 | even if we specify a fallback: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 188 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 189 | .. doctest:: |
| 190 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 191 | >>> topsecret.get('CompressionLevel', '3') |
| 192 | '9' |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 193 | |
| 194 | One more thing to be aware of is that the parser-level :meth:`get` method |
| 195 | provides a custom, more complex interface, maintained for backwards |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 196 | compatibility. When using this method, a fallback value can be provided via |
| 197 | the ``fallback`` keyword-only argument: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 198 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 199 | .. doctest:: |
| 200 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 201 | >>> config.get('bitbucket.org', 'monster', |
| 202 | ... fallback='No such things as monsters') |
| 203 | 'No such things as monsters' |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 204 | |
| 205 | The same ``fallback`` argument can be used with the :meth:`getint`, |
| 206 | :meth:`getfloat` and :meth:`getboolean` methods, for example: |
| 207 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 208 | .. doctest:: |
| 209 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 210 | >>> 'BatchMode' in topsecret |
| 211 | False |
| 212 | >>> topsecret.getboolean('BatchMode', fallback=True) |
| 213 | True |
| 214 | >>> config['DEFAULT']['BatchMode'] = 'no' |
| 215 | >>> topsecret.getboolean('BatchMode', fallback=True) |
| 216 | False |
| 217 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 218 | |
| 219 | Supported INI File Structure |
| 220 | ---------------------------- |
| 221 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 222 | A configuration file consists of sections, each led by a ``[section]`` header, |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 223 | followed by key/value entries separated by a specific string (``=`` or ``:`` by |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 224 | default [1]_). By default, section names are case sensitive but keys are not |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 225 | [1]_. Leading and trailing whitespace is removed from keys and values. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 226 | Values can be omitted, in which case the key/value delimiter may also be left |
| 227 | out. Values can also span multiple lines, as long as they are indented deeper |
| 228 | than the first line of the value. Depending on the parser's mode, blank lines |
| 229 | may be treated as parts of multiline values or ignored. |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 230 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 231 | Configuration files may include comments, prefixed by specific |
| 232 | characters (``#`` and ``;`` by default [1]_). Comments may appear on |
| 233 | their own on an otherwise empty line, or may be entered on lines holding |
| 234 | values or section names. In the latter case, they need to be preceded |
| 235 | by a whitespace character to be recognized as a comment. For backwards |
| 236 | compatibility, by default only ``;`` starts an inline comment, while |
| 237 | ``#`` does not [1]_. |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 238 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 239 | For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 240 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 241 | .. code-block:: ini |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 242 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 243 | [Simple Values] |
| 244 | key: value |
| 245 | spaces in keys: allowed |
| 246 | spaces in values: allowed as well |
| 247 | you can also use = to delimit keys from values |
| 248 | |
| 249 | [All Values Are Strings] |
| 250 | values like this: 1000000 |
| 251 | or this: 3.14159265359 |
| 252 | are they treated as numbers? : no |
| 253 | integers, floats and booleans are held as: strings |
| 254 | can use the API to get converted values directly: true |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 255 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 256 | [Multiline Values] |
| 257 | chorus: I'm a lumberjack, and I'm okay |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 258 | I sleep all night and I work all day |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 259 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 260 | [No Values] |
| 261 | key_without_value |
| 262 | empty string value here = |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 263 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 264 | [You can use comments] ; after a useful line |
| 265 | ; in an empty line |
| 266 | after: a_value ; here's another comment |
| 267 | inside: a ;comment |
| 268 | multiline ;comment |
| 269 | value! ;comment |
| 270 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 271 | [Sections Can Be Indented] |
| 272 | can_values_be_as_well = True |
| 273 | does_that_mean_anything_special = False |
| 274 | purpose = formatting for readability |
| 275 | multiline_values = are |
| 276 | handled just fine as |
| 277 | long as they are indented |
| 278 | deeper than the first line |
| 279 | of a value |
| 280 | # Did I mention we can indent comments, too? |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 281 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 282 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 283 | Interpolation of values |
| 284 | ----------------------- |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 285 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 286 | On top of the core functionality, :class:`SafeConfigParser` supports |
| 287 | interpolation. This means values can be preprocessed before returning them |
| 288 | from ``get()`` calls. |
| 289 | |
| 290 | .. class:: BasicInterpolation() |
| 291 | |
| 292 | The default implementation used by :class:`SafeConfigParser`. It enables |
| 293 | values to contain format strings which refer to other values in the same |
| 294 | section, or values in the special default section [1]_. Additional default |
| 295 | values can be provided on initialization. |
| 296 | |
| 297 | For example: |
| 298 | |
| 299 | .. code-block:: ini |
| 300 | |
| 301 | [Paths] |
| 302 | home_dir: /Users |
| 303 | my_dir: %(home_dir)s/lumberjack |
| 304 | my_pictures: %(my_dir)s/Pictures |
| 305 | |
| 306 | |
| 307 | In the example above, :class:`SafeConfigParser` with *interpolation* set to |
| 308 | ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of |
| 309 | ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would |
| 310 | resolve to ``/Users/lumberjack``. All interpolations are done on demand so |
| 311 | keys used in the chain of references do not have to be specified in any |
| 312 | specific order in the configuration file. |
| 313 | |
| 314 | With ``interpolation`` set to ``None``, the parser would simply return |
| 315 | ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and |
| 316 | ``%(home_dir)s/lumberjack`` as the value of ``my_dir``. |
| 317 | |
| 318 | .. class:: ExtendedInterpolation() |
| 319 | |
| 320 | An alternative handler for interpolation which implements a more advanced |
| 321 | syntax, used for instance in ``zc.buildout``. Extended interpolation is |
| 322 | using ``${section:option}`` to denote a value from a foreign section. |
| 323 | Interpolation can span multiple levels. For convenience, if the ``section:`` |
| 324 | part is omitted, interpolation defaults to the current section (and possibly |
| 325 | the default values from the special section). |
| 326 | |
| 327 | For example, the configuration specified above with basic interpolation, |
| 328 | would look like this with extended interpolation: |
| 329 | |
| 330 | .. code-block:: ini |
| 331 | |
| 332 | [Paths] |
| 333 | home_dir: /Users |
| 334 | my_dir: ${home_dir}/lumberjack |
| 335 | my_pictures: ${my_dir}/Pictures |
| 336 | |
| 337 | Values from other sections can be fetched as well: |
| 338 | |
| 339 | .. code-block:: ini |
| 340 | |
| 341 | [Common] |
| 342 | home_dir: /Users |
| 343 | library_dir: /Library |
| 344 | system_dir: /System |
| 345 | macports_dir: /opt/local |
| 346 | |
| 347 | [Frameworks] |
| 348 | Python: 3.2 |
| 349 | path: ${Common:system_dir}/Library/Frameworks/ |
| 350 | |
| 351 | [Arthur] |
| 352 | nickname: Two Sheds |
| 353 | last_name: Jackson |
| 354 | my_dir: ${Common:home_dir}/twosheds |
| 355 | my_pictures: ${my_dir}/Pictures |
| 356 | python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 357 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 358 | Mapping Protocol Access |
| 359 | ----------------------- |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 360 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 361 | .. versionadded:: 3.2 |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 362 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 363 | Mapping protocol access is a generic name for functionality that enables using |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 364 | custom objects as if they were dictionaries. In case of :mod:`configparser`, |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 365 | the mapping interface implementation is using the |
| 366 | ``parser['section']['option']`` notation. |
| 367 | |
| 368 | ``parser['section']`` in particular returns a proxy for the section's data in |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 369 | the parser. This means that the values are not copied but they are taken from |
| 370 | the original parser on demand. What's even more important is that when values |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 371 | are changed on a section proxy, they are actually mutated in the original |
| 372 | parser. |
| 373 | |
| 374 | :mod:`configparser` objects behave as close to actual dictionaries as possible. |
| 375 | The mapping interface is complete and adheres to the ``MutableMapping`` ABC. |
| 376 | However, there are a few differences that should be taken into account: |
| 377 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 378 | * By default, all keys in sections are accessible in a case-insensitive manner |
| 379 | [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed |
| 380 | option key names. This means lowercased keys by default. At the same time, |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 381 | for a section that holds the key ``'a'``, both expressions return ``True``:: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 382 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 383 | "a" in parser["section"] |
| 384 | "A" in parser["section"] |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 385 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 386 | * All sections include ``DEFAULTSECT`` values as well which means that |
| 387 | ``.clear()`` on a section may not leave the section visibly empty. This is |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 388 | because default values cannot be deleted from the section (because technically |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 389 | they are not there). If they are overriden in the section, deleting causes |
| 390 | the default value to be visible again. Trying to delete a default value |
| 391 | causes a ``KeyError``. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 392 | |
Éric Araujo | ff2a4ba | 2010-11-30 17:20:31 +0000 | [diff] [blame] | 393 | * Trying to delete the ``DEFAULTSECT`` raises ``ValueError``. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 394 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 395 | * There are two parser-level methods in the legacy API that hide the dictionary |
| 396 | interface and are incompatible: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 397 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 398 | * ``parser.get(section, option, **kwargs)`` - the second argument is **not** a |
| 399 | fallback value |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 400 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 401 | * ``parser.items(section)`` - this returns a list of *option*, *value* pairs |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 402 | for a specified ``section`` |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 403 | |
| 404 | The mapping protocol is implemented on top of the existing legacy API so that |
| 405 | subclassing the original interface makes the mappings work as expected as well. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 406 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 407 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 408 | Customizing Parser Behaviour |
| 409 | ---------------------------- |
| 410 | |
| 411 | There are nearly as many INI format variants as there are applications using it. |
| 412 | :mod:`configparser` goes a long way to provide support for the largest sensible |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 413 | set of INI styles available. The default functionality is mainly dictated by |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 414 | historical background and it's very likely that you will want to customize some |
| 415 | of the features. |
| 416 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 417 | The most common way to change the way a specific config parser works is to use |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 418 | the :meth:`__init__` options: |
| 419 | |
| 420 | * *defaults*, default value: ``None`` |
| 421 | |
| 422 | This option accepts a dictionary of key-value pairs which will be initially |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 423 | put in the ``DEFAULT`` section. This makes for an elegant way to support |
| 424 | concise configuration files that don't specify values which are the same as |
| 425 | the documented default. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 426 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 427 | Hint: if you want to specify default values for a specific section, use |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 428 | :meth:`read_dict` before you read the actual file. |
| 429 | |
| 430 | * *dict_type*, default value: :class:`collections.OrderedDict` |
| 431 | |
| 432 | This option has a major impact on how the mapping protocol will behave and how |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 433 | the written configuration files look. With the default ordered |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 434 | dictionary, every section is stored in the order they were added to the |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 435 | parser. Same goes for options within sections. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 436 | |
| 437 | An alternative dictionary type can be used for example to sort sections and |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 438 | options on write-back. You can also use a regular dictionary for performance |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 439 | reasons. |
| 440 | |
| 441 | Please note: there are ways to add a set of key-value pairs in a single |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 442 | operation. When you use a regular dictionary in those operations, the order |
| 443 | of the keys may be random. For example: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 444 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 445 | .. doctest:: |
| 446 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 447 | >>> parser = configparser.SafeConfigParser() |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 448 | >>> parser.read_dict({'section1': {'key1': 'value1', |
| 449 | ... 'key2': 'value2', |
| 450 | ... 'key3': 'value3'}, |
| 451 | ... 'section2': {'keyA': 'valueA', |
| 452 | ... 'keyB': 'valueB', |
| 453 | ... 'keyC': 'valueC'}, |
| 454 | ... 'section3': {'foo': 'x', |
| 455 | ... 'bar': 'y', |
| 456 | ... 'baz': 'z'} |
| 457 | ... }) |
| 458 | >>> parser.sections() |
| 459 | ['section3', 'section2', 'section1'] |
| 460 | >>> [option for option in parser['section3']] |
| 461 | ['baz', 'foo', 'bar'] |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 462 | |
| 463 | In these operations you need to use an ordered dictionary as well: |
| 464 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 465 | .. doctest:: |
| 466 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 467 | >>> from collections import OrderedDict |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 468 | >>> parser = configparser.SafeConfigParser() |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 469 | >>> parser.read_dict( |
| 470 | ... OrderedDict(( |
| 471 | ... ('s1', |
| 472 | ... OrderedDict(( |
| 473 | ... ('1', '2'), |
| 474 | ... ('3', '4'), |
| 475 | ... ('5', '6'), |
| 476 | ... )) |
| 477 | ... ), |
| 478 | ... ('s2', |
| 479 | ... OrderedDict(( |
| 480 | ... ('a', 'b'), |
| 481 | ... ('c', 'd'), |
| 482 | ... ('e', 'f'), |
| 483 | ... )) |
| 484 | ... ), |
| 485 | ... )) |
| 486 | ... ) |
| 487 | >>> parser.sections() |
| 488 | ['s1', 's2'] |
| 489 | >>> [option for option in parser['s1']] |
| 490 | ['1', '3', '5'] |
| 491 | >>> [option for option in parser['s2'].values()] |
| 492 | ['b', 'd', 'f'] |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 493 | |
| 494 | * *allow_no_value*, default value: ``False`` |
| 495 | |
| 496 | Some configuration files are known to include settings without values, but |
| 497 | which otherwise conform to the syntax supported by :mod:`configparser`. The |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 498 | *allow_no_value* parameter to the constructor can be used to |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 499 | indicate that such values should be accepted: |
| 500 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 501 | .. doctest:: |
| 502 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 503 | >>> import configparser |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 504 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 505 | >>> sample_config = """ |
| 506 | ... [mysqld] |
| 507 | ... user = mysql |
| 508 | ... pid-file = /var/run/mysqld/mysqld.pid |
| 509 | ... skip-external-locking |
| 510 | ... old_passwords = 1 |
| 511 | ... skip-bdb |
| 512 | ... skip-innodb # we don't need ACID today |
| 513 | ... """ |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 514 | >>> config = configparser.SafeConfigParser(allow_no_value=True) |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 515 | >>> config.read_string(sample_config) |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 516 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 517 | >>> # Settings with values are treated as before: |
| 518 | >>> config["mysqld"]["user"] |
| 519 | 'mysql' |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 520 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 521 | >>> # Settings without values provide None: |
| 522 | >>> config["mysqld"]["skip-bdb"] |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 523 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 524 | >>> # Settings which aren't specified still raise an error: |
| 525 | >>> config["mysqld"]["does-not-exist"] |
| 526 | Traceback (most recent call last): |
| 527 | ... |
| 528 | KeyError: 'does-not-exist' |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 529 | |
| 530 | * *delimiters*, default value: ``('=', ':')`` |
| 531 | |
| 532 | Delimiters are substrings that delimit keys from values within a section. The |
| 533 | first occurence of a delimiting substring on a line is considered a delimiter. |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 534 | This means values (but not keys) can contain the delimiters. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 535 | |
| 536 | See also the *space_around_delimiters* argument to |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 537 | :meth:`SafeConfigParser.write`. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 538 | |
| 539 | * *comment_prefixes*, default value: ``_COMPATIBLE`` (``'#'`` valid on empty |
| 540 | lines, ``';'`` valid also on non-empty lines) |
| 541 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 542 | Comment prefixes are strings that indicate the start of a valid comment |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 543 | within a config file. The peculiar default value allows for comments starting |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 544 | with ``'#'`` or ``';'`` but only the latter can be used in a non-empty line. |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 545 | This is obviously dictated by backwards compatibiliy. A more predictable |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 546 | approach would be to specify prefixes as ``('#', ';')`` which will allow for |
| 547 | both prefixes to be used in non-empty lines. |
| 548 | |
| 549 | Please note that config parsers don't support escaping of comment prefixes so |
| 550 | leaving characters out of *comment_prefixes* is a way of ensuring they can be |
| 551 | used as parts of keys or values. |
| 552 | |
| 553 | * *strict*, default value: ``False`` |
| 554 | |
| 555 | If set to ``True``, the parser will not allow for any section or option |
| 556 | duplicates while reading from a single source (using :meth:`read_file`, |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 557 | :meth:`read_string` or :meth:`read_dict`). The default is ``False`` only |
| 558 | because of backwards compatibility reasons. It is recommended to use strict |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 559 | parsers in new applications. |
| 560 | |
| 561 | * *empty_lines_in_values*, default value: ``True`` |
| 562 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 563 | In config parsers, values can span multiple lines as long as they are |
| 564 | indented more than the key that holds them. By default parsers also let |
| 565 | empty lines to be parts of values. At the same time, keys can be arbitrarily |
| 566 | indented themselves to improve readability. In consequence, when |
| 567 | configuration files get big and complex, it is easy for the user to lose |
| 568 | track of the file structure. Take for instance: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 569 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 570 | .. code-block:: ini |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 571 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 572 | [Section] |
| 573 | key = multiline |
| 574 | value with a gotcha |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 575 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 576 | this = is still a part of the multiline value of 'key' |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 577 | |
| 578 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 579 | This can be especially problematic for the user to see if she's using a |
| 580 | proportional font to edit the file. That is why when your application does |
| 581 | not need values with empty lines, you should consider disallowing them. This |
| 582 | will make empty lines split keys every time. In the example above, it would |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 583 | produce two keys, ``key`` and ``this``. |
| 584 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 585 | * *default_section*, default value: ``configparser.DEFAULTSECT`` (that is: |
| 586 | ``"DEFAULT"``) |
| 587 | |
| 588 | The convention of allowing a special section of default values for other |
| 589 | sections or interpolation purposes is a powerful concept of this library, |
| 590 | letting users create complex declarative configurations. This section is |
| 591 | normally called ``"DEFAULT"`` but this can be customized to point to any |
| 592 | other valid section name. Some typical values include: ``"general"`` or |
| 593 | ``"common"``. The name provided is used for recognizing default sections when |
| 594 | reading from any source and is used when writing configuration back to |
| 595 | a file. Its current value can be retrieved using the |
| 596 | ``parser_instance.default_section`` attribute and may be modified at runtime |
| 597 | (i.e. to convert files from one format to another). |
| 598 | |
| 599 | * *interpolation*, default value: ``configparser.BasicInterpolation`` |
| 600 | |
| 601 | Interpolation behaviour may be customized by providing a custom handler |
| 602 | through the *interpolation* argument. ``None`` can be used to turn off |
| 603 | interpolation completely, ``ExtendedInterpolation()`` provides a more |
| 604 | advanced variant inspired by ``zc.buildout``. More on the subject in the |
| 605 | `dedicated documentation section <#interpolation-of-values>`_. |
| 606 | |
| 607 | .. note:: :class:`RawConfigParser` is using ``None`` by default and |
| 608 | :class:`ConfigParser` is using ``configparser.BrokenInterpolation``. |
| 609 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 610 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 611 | More advanced customization may be achieved by overriding default values of |
| 612 | these parser attributes. The defaults are defined on the classes, so they |
| 613 | may be overriden by subclasses or by attribute assignment. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 614 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 615 | .. attribute:: BOOLEAN_STATES |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 616 | |
| 617 | By default when using :meth:`getboolean`, config parsers consider the |
| 618 | following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 619 | following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You |
| 620 | can override this by specifying a custom dictionary of strings and their |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 621 | Boolean outcomes. For example: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 622 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 623 | .. doctest:: |
| 624 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 625 | >>> custom = configparser.SafeConfigParser() |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 626 | >>> custom['section1'] = {'funky': 'nope'} |
| 627 | >>> custom['section1'].getboolean('funky') |
| 628 | Traceback (most recent call last): |
| 629 | ... |
| 630 | ValueError: Not a boolean: nope |
| 631 | >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False} |
| 632 | >>> custom['section1'].getboolean('funky') |
| 633 | False |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 634 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 635 | Other typical Boolean pairs include ``accept``/``reject`` or |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 636 | ``enabled``/``disabled``. |
| 637 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 638 | .. method:: optionxform(option) |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 639 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 640 | This method transforms option names on every read, get, or set |
| 641 | operation. The default converts the name to lowercase. This also |
| 642 | means that when a configuration file gets written, all keys will be |
| 643 | lowercase. Override this method if that's unsuitable. |
| 644 | For example: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 645 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 646 | .. doctest:: |
| 647 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 648 | >>> config = """ |
| 649 | ... [Section1] |
| 650 | ... Key = Value |
| 651 | ... |
| 652 | ... [Section2] |
| 653 | ... AnotherKey = Value |
| 654 | ... """ |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 655 | >>> typical = configparser.SafeConfigParser() |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 656 | >>> typical.read_string(config) |
| 657 | >>> list(typical['Section1'].keys()) |
| 658 | ['key'] |
| 659 | >>> list(typical['Section2'].keys()) |
| 660 | ['anotherkey'] |
| 661 | >>> custom = configparser.RawConfigParser() |
| 662 | >>> custom.optionxform = lambda option: option |
| 663 | >>> custom.read_string(config) |
| 664 | >>> list(custom['Section1'].keys()) |
| 665 | ['Key'] |
| 666 | >>> list(custom['Section2'].keys()) |
| 667 | ['AnotherKey'] |
| 668 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 669 | |
| 670 | Legacy API Examples |
| 671 | ------------------- |
| 672 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 673 | Mainly because of backwards compatibility concerns, :mod:`configparser` provides |
| 674 | also a legacy API with explicit ``get``/``set`` methods. While there are valid |
| 675 | use cases for the methods outlined below, mapping protocol access is preferred |
| 676 | for new projects. The legacy API is at times more advanced, low-level and |
| 677 | downright counterintuitive. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 678 | |
| 679 | An example of writing to a configuration file:: |
| 680 | |
| 681 | import configparser |
| 682 | |
| 683 | config = configparser.RawConfigParser() |
| 684 | |
| 685 | # Please note that using RawConfigParser's and the raw mode of |
| 686 | # ConfigParser's respective set functions, you can assign non-string values |
| 687 | # to keys internally, but will receive an error when attempting to write to |
| 688 | # a file or when you get it in non-raw mode. Setting values using the |
| 689 | # mapping protocol or SafeConfigParser's set() does not allow such |
| 690 | # assignments to take place. |
| 691 | config.add_section('Section1') |
| 692 | config.set('Section1', 'int', '15') |
| 693 | config.set('Section1', 'bool', 'true') |
| 694 | config.set('Section1', 'float', '3.1415') |
| 695 | config.set('Section1', 'baz', 'fun') |
| 696 | config.set('Section1', 'bar', 'Python') |
| 697 | config.set('Section1', 'foo', '%(bar)s is %(baz)s!') |
| 698 | |
| 699 | # Writing our configuration file to 'example.cfg' |
| 700 | with open('example.cfg', 'w') as configfile: |
| 701 | config.write(configfile) |
| 702 | |
| 703 | An example of reading the configuration file again:: |
| 704 | |
| 705 | import configparser |
| 706 | |
| 707 | config = configparser.RawConfigParser() |
| 708 | config.read('example.cfg') |
| 709 | |
| 710 | # getfloat() raises an exception if the value is not a float |
| 711 | # getint() and getboolean() also do this for their respective types |
| 712 | float = config.getfloat('Section1', 'float') |
| 713 | int = config.getint('Section1', 'int') |
| 714 | print(float + int) |
| 715 | |
| 716 | # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. |
| 717 | # This is because we are using a RawConfigParser(). |
| 718 | if config.getboolean('Section1', 'bool'): |
| 719 | print(config.get('Section1', 'foo')) |
| 720 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 721 | To get interpolation, use :class:`SafeConfigParser`:: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 722 | |
| 723 | import configparser |
| 724 | |
| 725 | cfg = configparser.SafeConfigParser() |
| 726 | cfg.read('example.cfg') |
| 727 | |
| 728 | # Set the optional `raw` argument of get() to True if you wish to disable |
| 729 | # interpolation in a single get operation. |
| 730 | print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!" |
| 731 | print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!" |
| 732 | |
| 733 | # The optional `vars` argument is a dict with members that will take |
| 734 | # precedence in interpolation. |
| 735 | print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation', |
| 736 | 'baz': 'evil'})) |
| 737 | |
| 738 | # The optional `fallback` argument can be used to provide a fallback value |
| 739 | print(cfg.get('Section1', 'foo')) |
| 740 | # -> "Python is fun!" |
| 741 | |
| 742 | print(cfg.get('Section1', 'foo', fallback='Monty is not.')) |
| 743 | # -> "Python is fun!" |
| 744 | |
| 745 | print(cfg.get('Section1', 'monster', fallback='No such things as monsters.')) |
| 746 | # -> "No such things as monsters." |
| 747 | |
| 748 | # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError |
| 749 | # but we can also use: |
| 750 | |
| 751 | print(cfg.get('Section1', 'monster', fallback=None)) |
| 752 | # -> None |
| 753 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 754 | Default values are available in all three types of ConfigParsers. They are |
| 755 | used in interpolation if an option used is not defined elsewhere. :: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 756 | |
| 757 | import configparser |
| 758 | |
| 759 | # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each |
| 760 | config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'}) |
| 761 | config.read('example.cfg') |
| 762 | |
| 763 | print(config.get('Section1', 'foo')) # -> "Python is fun!" |
| 764 | config.remove_option('Section1', 'bar') |
| 765 | config.remove_option('Section1', 'baz') |
| 766 | print(config.get('Section1', 'foo')) # -> "Life is hard!" |
| 767 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 768 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 769 | .. _safeconfigparser-objects: |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 770 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 771 | SafeConfigParser Objects |
| 772 | ------------------------ |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 773 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 774 | .. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 775 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 776 | The main configuration parser. When *defaults* is given, it is initialized |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 777 | into the dictionary of intrinsic defaults. When *dict_type* is given, it |
| 778 | will be used to create the dictionary objects for the list of sections, for |
| 779 | the options within a section, and for the default values. |
| 780 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 781 | When *delimiters* is given, it is used as the set of substrings that |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 782 | divide keys from values. When *comment_prefixes* is given, it will be used |
| 783 | as the set of substrings that prefix comments in a line, both for the whole |
| 784 | line and inline comments. For backwards compatibility, the default value for |
| 785 | *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can |
| 786 | start whole line comments while only ``;`` can start inline comments. |
| 787 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 788 | When *strict* is ``True`` (default: ``False``), the parser won't allow for |
| 789 | any section or option duplicates while reading from a single source (file, |
| 790 | string or dictionary), raising :exc:`DuplicateSectionError` or |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 791 | :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False`` |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 792 | (default: ``True``), each empty line marks the end of an option. Otherwise, |
| 793 | internal empty lines of a multiline option are kept as part of the value. |
| 794 | When *allow_no_value* is ``True`` (default: ``False``), options without |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 795 | values are accepted; the value held for these is ``None`` and they are |
| 796 | serialized without the trailing delimiter. |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 797 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 798 | When *default_section* is given, it specifies the name for the special |
| 799 | section holding default values for other sections and interpolation purposes |
| 800 | (normally named ``"DEFAULT"``). This value can be retrieved and changed on |
| 801 | runtime using the ``default_section`` instance attribute. |
| 802 | |
| 803 | Interpolation behaviour may be customized by providing a custom handler |
| 804 | through the *interpolation* argument. ``None`` can be used to turn off |
| 805 | interpolation completely, ``ExtendedInterpolation()`` provides a more |
| 806 | advanced variant inspired by ``zc.buildout``. More on the subject in the |
| 807 | `dedicated documentation section <#interpolation-of-values>`_. |
| 808 | |
| 809 | All option names used in interpolation will be passed through the |
| 810 | :meth:`optionxform` method just like any other option name reference. For |
| 811 | example, using the default implementation of :meth:`optionxform` (which |
| 812 | converts option names to lower case), the values ``foo %(bar)s`` and ``foo |
| 813 | %(BAR)s`` are equivalent. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 814 | |
Raymond Hettinger | 231b7f1 | 2009-03-03 00:23:19 +0000 | [diff] [blame] | 815 | .. versionchanged:: 3.1 |
Raymond Hettinger | 0663a1e | 2009-03-02 23:06:00 +0000 | [diff] [blame] | 816 | The default *dict_type* is :class:`collections.OrderedDict`. |
| 817 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 818 | .. versionchanged:: 3.2 |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 819 | *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*, |
| 820 | *empty_lines_in_values*, *default_section* and *interpolation* were |
| 821 | added. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 822 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 823 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 824 | .. method:: defaults() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 825 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 826 | Return a dictionary containing the instance-wide defaults. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 827 | |
| 828 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 829 | .. method:: sections() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 830 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 831 | Return a list of the sections available; the *default section* is not |
| 832 | included in the list. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 833 | |
| 834 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 835 | .. method:: add_section(section) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 836 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 837 | Add a section named *section* to the instance. If a section by the given |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 838 | name already exists, :exc:`DuplicateSectionError` is raised. If the |
Łukasz Langa | 2cf9ddb | 2010-12-04 12:46:01 +0000 | [diff] [blame^] | 839 | *default section* name is passed, :exc:`ValueError` is raised. The name |
| 840 | of the section must be a string; if not, :exc:`TypeError` is raised. |
| 841 | |
| 842 | .. versionchanged:: 3.2 |
| 843 | Non-string section names raise :exc:`TypeError`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 844 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 845 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 846 | .. method:: has_section(section) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 847 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 848 | Indicates whether the named *section* is present in the configuration. |
| 849 | The *default section* is not acknowledged. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 850 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 851 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 852 | .. method:: options(section) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 853 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 854 | Return a list of options available in the specified *section*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 855 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 856 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 857 | .. method:: has_option(section, option) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 858 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 859 | If the given *section* exists, and contains the given *option*, return |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 860 | :const:`True`; otherwise return :const:`False`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 861 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 862 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 863 | .. method:: read(filenames, encoding=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 864 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 865 | Attempt to read and parse a list of filenames, returning a list of |
| 866 | filenames which were successfully parsed. If *filenames* is a string, it |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 867 | is treated as a single filename. If a file named in *filenames* cannot |
| 868 | be opened, that file will be ignored. This is designed so that you can |
| 869 | specify a list of potential configuration file locations (for example, |
| 870 | the current directory, the user's home directory, and some system-wide |
| 871 | directory), and all existing configuration files in the list will be |
| 872 | read. If none of the named files exist, the :class:`ConfigParser` |
| 873 | instance will contain an empty dataset. An application which requires |
| 874 | initial values to be loaded from a file should load the required file or |
| 875 | files using :meth:`read_file` before calling :meth:`read` for any |
| 876 | optional files:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 877 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 878 | import configparser, os |
Georg Brandl | 8dcaa73 | 2010-07-29 12:17:40 +0000 | [diff] [blame] | 879 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 880 | config = configparser.SafeConfigParser() |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 881 | config.read_file(open('defaults.cfg')) |
| 882 | config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], |
| 883 | encoding='cp1250') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 884 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 885 | .. versionadded:: 3.2 |
| 886 | The *encoding* parameter. Previously, all files were read using the |
| 887 | default encoding for :func:`open`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 888 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 889 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 890 | .. method:: read_file(f, source=None) |
Georg Brandl | 73753d3 | 2009-09-22 13:53:14 +0000 | [diff] [blame] | 891 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 892 | Read and parse configuration data from the file or file-like object in |
| 893 | *f* (only the :meth:`readline` method is used). The file-like object |
| 894 | must operate in text mode. Specifically, it must return strings from |
| 895 | :meth:`readline`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 896 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 897 | Optional argument *source* specifies the name of the file being read. If |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 898 | not given and *f* has a :attr:`name` attribute, that is used for |
| 899 | *source*; the default is ``'<???>'``. |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 900 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 901 | .. versionadded:: 3.2 |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 902 | Replaces :meth:`readfp`. |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 903 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 904 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 905 | .. method:: read_string(string, source='<string>') |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 906 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 907 | Parse configuration data from a string. |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 908 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 909 | Optional argument *source* specifies a context-specific name of the |
| 910 | string passed. If not given, ``'<string>'`` is used. This should |
| 911 | commonly be a filesystem path or a URL. |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 912 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 913 | .. versionadded:: 3.2 |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 914 | |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 915 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 916 | .. method:: read_dict(dictionary, source='<dict>') |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 917 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 918 | Load configuration from a dictionary. Keys are section names, values are |
| 919 | dictionaries with keys and values that should be present in the section. |
| 920 | If the used dictionary type preserves order, sections and their keys will |
| 921 | be added in order. Values are automatically converted to strings. |
Fred Drake | a492362 | 2010-08-09 12:52:45 +0000 | [diff] [blame] | 922 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 923 | Optional argument *source* specifies a context-specific name of the |
| 924 | dictionary passed. If not given, ``<dict>`` is used. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 925 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 926 | .. versionadded:: 3.2 |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 927 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 928 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 929 | .. method:: get(section, option, raw=False, [vars, fallback]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 930 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 931 | Get an *option* value for the named *section*. If *vars* is provided, it |
| 932 | must be a dictionary. The *option* is looked up in *vars* (if provided), |
| 933 | *section*, and in *DEFAULTSECT* in that order. If the key is not found |
| 934 | and *fallback* is provided, it is used as a fallback value. ``None`` can |
| 935 | be provided as a *fallback* value. |
Georg Brandl | 470a123 | 2010-07-29 14:17:12 +0000 | [diff] [blame] | 936 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 937 | All the ``'%'`` interpolations are expanded in the return values, unless |
| 938 | the *raw* argument is true. Values for interpolation keys are looked up |
| 939 | in the same manner as the option. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 940 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 941 | .. versionchanged:: 3.2 |
| 942 | Arguments *raw*, *vars* and *fallback* are keyword only to protect |
| 943 | users from trying to use the third argument as the *fallback* fallback |
| 944 | (especially when using the mapping protocol). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 945 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 946 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 947 | .. method:: getint(section, option, raw=False, [vars, fallback]) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 948 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 949 | A convenience method which coerces the *option* in the specified *section* |
| 950 | to an integer. See :meth:`get` for explanation of *raw*, *vars* and |
| 951 | *fallback*. |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 952 | |
| 953 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 954 | .. method:: getfloat(section, option, raw=False, [vars, fallback]) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 955 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 956 | A convenience method which coerces the *option* in the specified *section* |
| 957 | to a floating point number. See :meth:`get` for explanation of *raw*, |
| 958 | *vars* and *fallback*. |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 959 | |
| 960 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 961 | .. method:: getboolean(section, option, raw=False, [vars, fallback]) |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 962 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 963 | A convenience method which coerces the *option* in the specified *section* |
| 964 | to a Boolean value. Note that the accepted values for the option are |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 965 | ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to |
| 966 | return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 967 | cause it to return ``False``. These string values are checked in a |
| 968 | case-insensitive manner. Any other value will cause it to raise |
| 969 | :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and |
| 970 | *fallback*. |
Fred Drake | cc645b9 | 2010-09-04 04:35:34 +0000 | [diff] [blame] | 971 | |
| 972 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 973 | .. method:: items(section, raw=False, vars=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 974 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 975 | Return a list of *name*, *value* pairs for the options in the given |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 976 | *section*. Optional arguments have the same meaning as for the |
| 977 | :meth:`get` method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 978 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 979 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 980 | .. method:: set(section, option, value) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 981 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 982 | If the given section exists, set the given option to the specified value; |
Łukasz Langa | 2cf9ddb | 2010-12-04 12:46:01 +0000 | [diff] [blame^] | 983 | otherwise raise :exc:`NoSectionError`. *option* and *value* must be |
| 984 | strings; if not, :exc:`TypeError` is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 985 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 986 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 987 | .. method:: write(fileobject, space_around_delimiters=True) |
| 988 | |
| 989 | Write a representation of the configuration to the specified :term:`file |
| 990 | object`, which must be opened in text mode (accepting strings). This |
| 991 | representation can be parsed by a future :meth:`read` call. If |
| 992 | *space_around_delimiters* is true, delimiters between |
| 993 | keys and values are surrounded by spaces. |
| 994 | |
| 995 | |
| 996 | .. method:: remove_option(section, option) |
| 997 | |
| 998 | Remove the specified *option* from the specified *section*. If the |
| 999 | section does not exist, raise :exc:`NoSectionError`. If the option |
| 1000 | existed to be removed, return :const:`True`; otherwise return |
| 1001 | :const:`False`. |
| 1002 | |
| 1003 | |
| 1004 | .. method:: remove_section(section) |
| 1005 | |
| 1006 | Remove the specified *section* from the configuration. If the section in |
| 1007 | fact existed, return ``True``. Otherwise return ``False``. |
| 1008 | |
| 1009 | |
| 1010 | .. method:: optionxform(option) |
| 1011 | |
| 1012 | Transforms the option name *option* as found in an input file or as passed |
| 1013 | in by client code to the form that should be used in the internal |
| 1014 | structures. The default implementation returns a lower-case version of |
| 1015 | *option*; subclasses may override this or client code can set an attribute |
| 1016 | of this name on instances to affect this behavior. |
| 1017 | |
| 1018 | You don't need to subclass the parser to use this method, you can also |
| 1019 | set it on an instance, to a function that takes a string argument and |
| 1020 | returns a string. Setting it to ``str``, for example, would make option |
| 1021 | names case sensitive:: |
| 1022 | |
| 1023 | cfgparser = ConfigParser() |
| 1024 | cfgparser.optionxform = str |
| 1025 | |
| 1026 | Note that when reading configuration files, whitespace around the option |
| 1027 | names is stripped before :meth:`optionxform` is called. |
| 1028 | |
| 1029 | |
| 1030 | .. method:: readfp(fp, filename=None) |
| 1031 | |
| 1032 | .. deprecated:: 3.2 |
| 1033 | Use :meth:`read_file` instead. |
| 1034 | |
| 1035 | |
| 1036 | .. data:: MAX_INTERPOLATION_DEPTH |
| 1037 | |
| 1038 | The maximum depth for recursive interpolation for :meth:`get` when the *raw* |
| 1039 | parameter is false. This is relevant only when the default *interpolation* |
| 1040 | is used. |
| 1041 | |
| 1042 | |
| 1043 | .. _rawconfigparser-objects: |
| 1044 | |
| 1045 | RawConfigParser Objects |
| 1046 | ----------------------- |
| 1047 | |
| 1048 | .. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True, default_section=configaparser.DEFAULTSECT, interpolation=None) |
| 1049 | |
| 1050 | Legacy variant of the :class:`SafeConfigParser` with interpolation disabled |
Łukasz Langa | 2cf9ddb | 2010-12-04 12:46:01 +0000 | [diff] [blame^] | 1051 | by default and unsafe ``add_section`` and ``set`` methods. |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 1052 | |
| 1053 | .. note:: |
| 1054 | Consider using :class:`SafeConfigParser` instead which checks types of |
| 1055 | the values to be stored internally. If you don't want interpolation, you |
| 1056 | can use ``SafeConfigParser(interpolation=None)``. |
| 1057 | |
| 1058 | |
Łukasz Langa | 2cf9ddb | 2010-12-04 12:46:01 +0000 | [diff] [blame^] | 1059 | .. method:: add_section(section) |
| 1060 | |
| 1061 | Add a section named *section* to the instance. If a section by the given |
| 1062 | name already exists, :exc:`DuplicateSectionError` is raised. If the |
| 1063 | *default section* name is passed, :exc:`ValueError` is raised. |
| 1064 | |
| 1065 | Type of *section* is not checked which lets users create non-string named |
| 1066 | sections. This behaviour is unsupported and may cause internal errors. |
| 1067 | |
| 1068 | |
Łukasz Langa | b6a6f5f | 2010-12-03 16:28:00 +0000 | [diff] [blame] | 1069 | .. method:: set(section, option, value) |
| 1070 | |
| 1071 | If the given section exists, set the given option to the specified value; |
| 1072 | otherwise raise :exc:`NoSectionError`. While it is possible to use |
| 1073 | :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters |
| 1074 | set to true) for *internal* storage of non-string values, full |
| 1075 | functionality (including interpolation and output to files) can only be |
| 1076 | achieved using string values. |
| 1077 | |
| 1078 | This method lets users assign non-string values to keys internally. This |
| 1079 | behaviour is unsupported and will cause errors when attempting to write |
| 1080 | to a file or get it in non-raw mode. **Use the mapping protocol API** |
| 1081 | which does not allow such assignments to take place. |
| 1082 | |
| 1083 | |
| 1084 | .. _configparser-objects: |
| 1085 | |
| 1086 | ConfigParser Objects |
| 1087 | -------------------- |
| 1088 | |
| 1089 | .. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BrokenInterpolation()) |
| 1090 | |
| 1091 | .. deprecated:: 3.2 |
| 1092 | Whenever you can, consider using :class:`SafeConfigParser`. The |
| 1093 | :class:`ConfigParser` provides the same functionality but its |
| 1094 | implementation is less predictable. It does not validate the |
| 1095 | interpolation syntax used within a configuration file. It also does not |
| 1096 | enable escaping the interpolation character (when using |
| 1097 | :class:`SafeConfigParser`, a key can have ``%`` as part of the value by |
| 1098 | specifying ``%%`` in the file). On top of that, this class doesn't ensure |
| 1099 | whether values passed to the parser object are strings which may lead to |
| 1100 | inconsistent internal state. |
| 1101 | |
| 1102 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1103 | Exceptions |
| 1104 | ---------- |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1105 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1106 | .. exception:: Error |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1107 | |
Fred Drake | 5a7c11f | 2010-11-13 05:24:17 +0000 | [diff] [blame] | 1108 | Base class for all other :mod:`configparser` exceptions. |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1109 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1110 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1111 | .. exception:: NoSectionError |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1112 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1113 | Exception raised when a specified section is not found. |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1114 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1115 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1116 | .. exception:: DuplicateSectionError |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1117 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1118 | Exception raised if :meth:`add_section` is called with the name of a section |
| 1119 | that is already present or in strict parsers when a section if found more |
| 1120 | than once in a single input file, string or dictionary. |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1121 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1122 | .. versionadded:: 3.2 |
| 1123 | Optional ``source`` and ``lineno`` attributes and arguments to |
| 1124 | :meth:`__init__` were added. |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1125 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1126 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1127 | .. exception:: DuplicateOptionError |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1128 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1129 | Exception raised by strict parsers if a single option appears twice during |
| 1130 | reading from a single file, string or dictionary. This catches misspellings |
| 1131 | and case sensitivity-related errors, e.g. a dictionary may have two keys |
| 1132 | representing the same case-insensitive configuration key. |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1133 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1134 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1135 | .. exception:: NoOptionError |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1136 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1137 | Exception raised when a specified option is not found in the specified |
| 1138 | section. |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1139 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1140 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1141 | .. exception:: InterpolationError |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1142 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1143 | Base class for exceptions raised when problems occur performing string |
| 1144 | interpolation. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1145 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1146 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1147 | .. exception:: InterpolationDepthError |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 1148 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1149 | Exception raised when string interpolation cannot be completed because the |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 1150 | number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1151 | :exc:`InterpolationError`. |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1152 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1153 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1154 | .. exception:: InterpolationMissingOptionError |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1155 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 1156 | Exception raised when an option referenced from a value does not exist. |
| 1157 | Subclass of :exc:`InterpolationError`. |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1158 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1159 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1160 | .. exception:: InterpolationSyntaxError |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1161 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 1162 | Exception raised when the source text into which substitutions are made does |
| 1163 | not conform to the required syntax. Subclass of :exc:`InterpolationError`. |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 1164 | |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1165 | |
| 1166 | .. exception:: MissingSectionHeaderError |
| 1167 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 1168 | Exception raised when attempting to parse a file which has no section |
| 1169 | headers. |
Łukasz Langa | 26d513c | 2010-11-10 18:57:39 +0000 | [diff] [blame] | 1170 | |
| 1171 | |
| 1172 | .. exception:: ParsingError |
| 1173 | |
| 1174 | Exception raised when errors occur attempting to parse a file. |
| 1175 | |
| 1176 | .. versionchanged:: 3.2 |
| 1177 | The ``filename`` attribute and :meth:`__init__` argument were renamed to |
| 1178 | ``source`` for consistency. |
| 1179 | |
Georg Brandl | bb27c12 | 2010-11-11 07:26:40 +0000 | [diff] [blame] | 1180 | |
| 1181 | .. rubric:: Footnotes |
| 1182 | |
| 1183 | .. [1] Config parsers allow for heavy customization. If you are interested in |
| 1184 | changing the behaviour outlined by the footnote reference, consult the |
| 1185 | `Customizing Parser Behaviour`_ section. |