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