| 1 |
:mod:`!configparser` --- Configuration file parser |
| 2 |
================================================== |
| 3 |
|
| 4 |
.. module:: configparser |
| 5 |
:synopsis: Configuration file parser. |
| 6 |
|
| 7 |
.. moduleauthor:: Ken Manheimer <[email protected]> |
| 8 |
.. moduleauthor:: Barry Warsaw <[email protected]> |
| 9 |
.. moduleauthor:: Eric S. Raymond <[email protected]> |
| 10 |
.. moduleauthor:: Łukasz Langa <[email protected]> |
| 11 |
.. sectionauthor:: Christopher G. Petrilli <[email protected]> |
| 12 |
.. sectionauthor:: Łukasz Langa <[email protected]> |
| 13 |
|
| 14 |
**Source code:** :source:`Lib/configparser.py` |
| 15 |
|
| 16 |
.. index:: |
| 17 |
pair: .ini; file |
| 18 |
pair: configuration; file |
| 19 |
single: ini file |
| 20 |
single: Windows ini file |
| 21 |
|
| 22 |
-------------- |
| 23 |
|
| 24 |
This module provides the :class:`ConfigParser` class which implements a basic |
| 25 |
configuration language which provides a structure similar to what's found in |
| 26 |
Microsoft Windows INI files. You can use this to write Python programs which |
| 27 |
can be customized by end users easily. |
| 28 |
|
| 29 |
.. note:: |
| 30 |
|
| 31 |
This library does *not* interpret or write the value-type prefixes used in |
| 32 |
the Windows Registry extended version of INI syntax. |
| 33 |
|
| 34 |
.. seealso:: |
| 35 |
|
| 36 |
Module :mod:`tomllib` |
| 37 |
TOML is a well-specified format for application configuration files. |
| 38 |
It is specifically designed to be an improved version of INI. |
| 39 |
|
| 40 |
Module :mod:`shlex` |
| 41 |
Support for creating Unix shell-like mini-languages which can also |
| 42 |
be used for application configuration files. |
| 43 |
|
| 44 |
Module :mod:`json` |
| 45 |
The ``json`` module implements a subset of JavaScript syntax which is |
| 46 |
sometimes used for configuration, but does not support comments. |
| 47 |
|
| 48 |
|
| 49 |
.. testsetup:: |
| 50 |
|
| 51 |
import configparser |
| 52 |
|
| 53 |
.. testcleanup:: |
| 54 |
|
| 55 |
import os |
| 56 |
os.remove("example.ini") |
| 57 |
os.remove("override.ini") |
| 58 |
|
| 59 |
|
| 60 |
Quick Start |
| 61 |
----------- |
| 62 |
|
| 63 |
Let's take a very basic configuration file that looks like this: |
| 64 |
|
| 65 |
.. code-block:: ini |
| 66 |
|
| 67 |
[DEFAULT] |
| 68 |
ServerAliveInterval = 45 |
| 69 |
Compression = yes |
| 70 |
CompressionLevel = 9 |
| 71 |
ForwardX11 = yes |
| 72 |
|
| 73 |
[forge.example] |
| 74 |
User = hg |
| 75 |
|
| 76 |
[topsecret.server.example] |
| 77 |
Port = 50022 |
| 78 |
ForwardX11 = no |
| 79 |
|
| 80 |
The structure of INI files is described `in the following section |
| 81 |
<#supported-ini-file-structure>`_. Essentially, the file |
| 82 |
consists of sections, each of which contains keys with values. |
| 83 |
:mod:`!configparser` classes can read and write such files. Let's start by |
| 84 |
creating the above configuration file programmatically. |
| 85 |
|
| 86 |
.. doctest:: |
| 87 |
|
| 88 |
>>> import configparser |
| 89 |
>>> config = configparser.ConfigParser() |
| 90 |
>>> config['DEFAULT'] = {'ServerAliveInterval': '45', |
| 91 |
... 'Compression': 'yes', |
| 92 |
... 'CompressionLevel': '9'} |
| 93 |
>>> config['forge.example'] = {} |
| 94 |
>>> config['forge.example']['User'] = 'hg' |
| 95 |
>>> config['topsecret.server.example'] = {} |
| 96 |
>>> topsecret = config['topsecret.server.example'] |
| 97 |
>>> topsecret['Port'] = '50022' # mutates the parser |
| 98 |
>>> topsecret['ForwardX11'] = 'no' # same here |
| 99 |
>>> config['DEFAULT']['ForwardX11'] = 'yes' |
| 100 |
>>> with open('example.ini', 'w') as configfile: |
| 101 |
... config.write(configfile) |
| 102 |
... |
| 103 |
|
| 104 |
As you can see, we can treat a config parser much like a dictionary. |
| 105 |
There are differences, `outlined later <#mapping-protocol-access>`_, but |
| 106 |
the behavior is very close to what you would expect from a dictionary. |
| 107 |
|
| 108 |
Now that we have created and saved a configuration file, let's read it |
| 109 |
back and explore the data it holds. |
| 110 |
|
| 111 |
.. doctest:: |
| 112 |
|
| 113 |
>>> config = configparser.ConfigParser() |
| 114 |
>>> config.sections() |
| 115 |
[] |
| 116 |
>>> config.read('example.ini') |
| 117 |
['example.ini'] |
| 118 |
>>> config.sections() |
| 119 |
['forge.example', 'topsecret.server.example'] |
| 120 |
>>> 'forge.example' in config |
| 121 |
True |
| 122 |
>>> 'python.org' in config |
| 123 |
False |
| 124 |
>>> config['forge.example']['User'] |
| 125 |
'hg' |
| 126 |
>>> config['DEFAULT']['Compression'] |
| 127 |
'yes' |
| 128 |
>>> topsecret = config['topsecret.server.example'] |
| 129 |
>>> topsecret['ForwardX11'] |
| 130 |
'no' |
| 131 |
>>> topsecret['Port'] |
| 132 |
'50022' |
| 133 |
>>> for key in config['forge.example']: # doctest: +SKIP |
| 134 |
... print(key) |
| 135 |
user |
| 136 |
compressionlevel |
| 137 |
serveraliveinterval |
| 138 |
compression |
| 139 |
forwardx11 |
| 140 |
>>> config['forge.example']['ForwardX11'] |
| 141 |
'yes' |
| 142 |
|
| 143 |
As we can see above, the API is pretty straightforward. The only bit of magic |
| 144 |
involves the ``DEFAULT`` section which provides default values for all other |
| 145 |
sections [1]_. Note also that keys in sections are |
| 146 |
case-insensitive and stored in lowercase [1]_. |
| 147 |
|
| 148 |
It is possible to read several configurations into a single |
| 149 |
:class:`ConfigParser`, where the most recently added configuration has the |
| 150 |
highest priority. Any conflicting keys are taken from the more recent |
| 151 |
configuration while the previously existing keys are retained. The example |
| 152 |
below reads in an ``override.ini`` file, which will override any conflicting |
| 153 |
keys from the ``example.ini`` file. |
| 154 |
|
| 155 |
.. code-block:: ini |
| 156 |
|
| 157 |
[DEFAULT] |
| 158 |
ServerAliveInterval = -1 |
| 159 |
|
| 160 |
.. doctest:: |
| 161 |
|
| 162 |
>>> config_override = configparser.ConfigParser() |
| 163 |
>>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'} |
| 164 |
>>> with open('override.ini', 'w') as configfile: |
| 165 |
... config_override.write(configfile) |
| 166 |
... |
| 167 |
>>> config_override = configparser.ConfigParser() |
| 168 |
>>> config_override.read(['example.ini', 'override.ini']) |
| 169 |
['example.ini', 'override.ini'] |
| 170 |
>>> print(config_override.get('DEFAULT', 'ServerAliveInterval')) |
| 171 |
-1 |
| 172 |
|
| 173 |
|
| 174 |
This behaviour is equivalent to a :meth:`ConfigParser.read` call with several |
| 175 |
files passed to the *filenames* parameter. |
| 176 |
|
| 177 |
|
| 178 |
Supported Datatypes |
| 179 |
------------------- |
| 180 |
|
| 181 |
Config parsers do not guess datatypes of values in configuration files, always |
| 182 |
storing them internally as strings. This means that if you need other |
| 183 |
datatypes, you should convert on your own: |
| 184 |
|
| 185 |
.. doctest:: |
| 186 |
|
| 187 |
>>> int(topsecret['Port']) |
| 188 |
50022 |
| 189 |
>>> float(topsecret['CompressionLevel']) |
| 190 |
9.0 |
| 191 |
|
| 192 |
Since this task is so common, config parsers provide a range of handy getter |
| 193 |
methods to handle integers, floats and booleans. The last one is the most |
| 194 |
interesting because simply passing the value to ``bool()`` would do no good |
| 195 |
since ``bool('False')`` is still ``True``. This is why config parsers also |
| 196 |
provide :meth:`~ConfigParser.getboolean`. This method is case-insensitive and |
| 197 |
recognizes Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``, |
| 198 |
``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example: |
| 199 |
|
| 200 |
.. doctest:: |
| 201 |
|
| 202 |
>>> topsecret.getboolean('ForwardX11') |
| 203 |
False |
| 204 |
>>> config['forge.example'].getboolean('ForwardX11') |
| 205 |
True |
| 206 |
>>> config.getboolean('forge.example', 'Compression') |
| 207 |
True |
| 208 |
|
| 209 |
Apart from :meth:`~ConfigParser.getboolean`, config parsers also |
| 210 |
provide equivalent :meth:`~ConfigParser.getint` and |
| 211 |
:meth:`~ConfigParser.getfloat` methods. You can register your own |
| 212 |
converters and customize the provided ones. [1]_ |
| 213 |
|
| 214 |
Fallback Values |
| 215 |
--------------- |
| 216 |
|
| 217 |
As with a dictionary, you can use a section's :meth:`~ConfigParser.get` method to |
| 218 |
provide fallback values: |
| 219 |
|
| 220 |
.. doctest:: |
| 221 |
|
| 222 |
>>> topsecret.get('Port') |
| 223 |
'50022' |
| 224 |
>>> topsecret.get('CompressionLevel') |
| 225 |
'9' |
| 226 |
>>> topsecret.get('Cipher') |
| 227 |
>>> topsecret.get('Cipher', '3des-cbc') |
| 228 |
'3des-cbc' |
| 229 |
|
| 230 |
Please note that default values have precedence over fallback values. |
| 231 |
For instance, in our example the ``'CompressionLevel'`` key was |
| 232 |
specified only in the ``'DEFAULT'`` section. If we try to get it from |
| 233 |
the section ``'topsecret.server.example'``, we will always get the default, |
| 234 |
even if we specify a fallback: |
| 235 |
|
| 236 |
.. doctest:: |
| 237 |
|
| 238 |
>>> topsecret.get('CompressionLevel', '3') |
| 239 |
'9' |
| 240 |
|
| 241 |
One more thing to be aware of is that the parser-level :meth:`~ConfigParser.get` method |
| 242 |
provides a custom, more complex interface, maintained for backwards |
| 243 |
compatibility. When using this method, a fallback value can be provided via |
| 244 |
the ``fallback`` keyword-only argument: |
| 245 |
|
| 246 |
.. doctest:: |
| 247 |
|
| 248 |
>>> config.get('forge.example', 'monster', |
| 249 |
... fallback='No such things as monsters') |
| 250 |
'No such things as monsters' |
| 251 |
|
| 252 |
The same ``fallback`` argument can be used with the |
| 253 |
:meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` and |
| 254 |
:meth:`~ConfigParser.getboolean` methods, for example: |
| 255 |
|
| 256 |
.. doctest:: |
| 257 |
|
| 258 |
>>> 'BatchMode' in topsecret |
| 259 |
False |
| 260 |
>>> topsecret.getboolean('BatchMode', fallback=True) |
| 261 |
True |
| 262 |
>>> config['DEFAULT']['BatchMode'] = 'no' |
| 263 |
>>> topsecret.getboolean('BatchMode', fallback=True) |
| 264 |
False |
| 265 |
|
| 266 |
|
| 267 |
Supported INI File Structure |
| 268 |
---------------------------- |
| 269 |
|
| 270 |
A configuration file consists of sections, each led by a ``[section]`` header, |
| 271 |
followed by key/value entries separated by a specific string (``=`` or ``:`` by |
| 272 |
default [1]_). By default, section names are case sensitive but keys are not |
| 273 |
[1]_. Leading and trailing whitespace is removed from keys and values. |
| 274 |
Values can be omitted if the parser is configured to allow it [1]_, |
| 275 |
in which case the key/value delimiter may also be left |
| 276 |
out. Values can also span multiple lines, as long as they are indented deeper |
| 277 |
than the first line of the value. Depending on the parser's mode, blank lines |
| 278 |
may be treated as parts of multiline values or ignored. |
| 279 |
|
| 280 |
By default, a valid section name can be any string that does not contain '\\n'. |
| 281 |
To change this, see :attr:`ConfigParser.SECTCRE`. |
| 282 |
|
| 283 |
The first section name may be omitted if the parser is configured to allow an |
| 284 |
unnamed top level section with ``allow_unnamed_section=True``. In this case, |
| 285 |
the keys/values may be retrieved by :const:`UNNAMED_SECTION` as in |
| 286 |
``config[UNNAMED_SECTION]``. |
| 287 |
|
| 288 |
Configuration files may include comments, prefixed by specific |
| 289 |
characters (``#`` and ``;`` by default [1]_). Comments may appear on |
| 290 |
their own on an otherwise empty line, possibly indented. [1]_ |
| 291 |
|
| 292 |
For example: |
| 293 |
|
| 294 |
.. code-block:: ini |
| 295 |
|
| 296 |
[Simple Values] |
| 297 |
key=value |
| 298 |
spaces in keys=allowed |
| 299 |
spaces in values=allowed as well |
| 300 |
spaces around the delimiter = obviously |
| 301 |
you can also use : to delimit keys from values |
| 302 |
|
| 303 |
[All Values Are Strings] |
| 304 |
values like this: 1000000 |
| 305 |
or this: 3.14159265359 |
| 306 |
are they treated as numbers? : no |
| 307 |
integers, floats and booleans are held as: strings |
| 308 |
can use the API to get converted values directly: true |
| 309 |
|
| 310 |
[Multiline Values] |
| 311 |
chorus: I'm a lumberjack, and I'm okay |
| 312 |
I sleep all night and I work all day |
| 313 |
|
| 314 |
[No Values] |
| 315 |
key_without_value |
| 316 |
empty string value here = |
| 317 |
|
| 318 |
[You can use comments] |
| 319 |
# like this |
| 320 |
; or this |
| 321 |
|
| 322 |
# By default only in an empty line. |
| 323 |
# Inline comments can be harmful because they prevent users |
| 324 |
# from using the delimiting characters as parts of values. |
| 325 |
# That being said, this can be customized. |
| 326 |
|
| 327 |
[Sections Can Be Indented] |
| 328 |
can_values_be_as_well = True |
| 329 |
does_that_mean_anything_special = False |
| 330 |
purpose = formatting for readability |
| 331 |
multiline_values = are |
| 332 |
handled just fine as |
| 333 |
long as they are indented |
| 334 |
deeper than the first line |
| 335 |
of a value |
| 336 |
# Did I mention we can indent comments, too? |
| 337 |
|
| 338 |
|
| 339 |
.. _unnamed-sections: |
| 340 |
|
| 341 |
Unnamed Sections |
| 342 |
---------------- |
| 343 |
|
| 344 |
The name of the first section (or unique) may be omitted and values |
| 345 |
retrieved by the :const:`UNNAMED_SECTION` attribute. |
| 346 |
|
| 347 |
.. doctest:: |
| 348 |
|
| 349 |
>>> config = """ |
| 350 |
... option = value |
| 351 |
... |
| 352 |
... [ Section 2 ] |
| 353 |
... another = val |
| 354 |
... """ |
| 355 |
>>> unnamed = configparser.ConfigParser(allow_unnamed_section=True) |
| 356 |
>>> unnamed.read_string(config) |
| 357 |
>>> unnamed.get(configparser.UNNAMED_SECTION, 'option') |
| 358 |
'value' |
| 359 |
|
| 360 |
Interpolation of values |
| 361 |
----------------------- |
| 362 |
|
| 363 |
On top of the core functionality, :class:`ConfigParser` supports |
| 364 |
interpolation. This means values can be preprocessed before returning them |
| 365 |
from ``get()`` calls. |
| 366 |
|
| 367 |
.. index:: single: % (percent); interpolation in configuration files |
| 368 |
|
| 369 |
.. class:: BasicInterpolation() |
| 370 |
|
| 371 |
The default implementation used by :class:`ConfigParser`. It enables |
| 372 |
values to contain format strings which refer to other values in the same |
| 373 |
section, or values in the special default section [1]_. Additional default |
| 374 |
values can be provided on initialization. |
| 375 |
|
| 376 |
For example: |
| 377 |
|
| 378 |
.. code-block:: ini |
| 379 |
|
| 380 |
[Paths] |
| 381 |
home_dir: /Users |
| 382 |
my_dir: %(home_dir)s/lumberjack |
| 383 |
my_pictures: %(my_dir)s/Pictures |
| 384 |
|
| 385 |
[Escape] |
| 386 |
# use a %% to escape the % sign (% is the only character that needs to be escaped): |
| 387 |
gain: 80%% |
| 388 |
|
| 389 |
In the example above, :class:`ConfigParser` with *interpolation* set to |
| 390 |
``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of |
| 391 |
``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would |
| 392 |
resolve to ``/Users/lumberjack``. All interpolations are done on demand so |
| 393 |
keys used in the chain of references do not have to be specified in any |
| 394 |
specific order in the configuration file. |
| 395 |
|
| 396 |
With ``interpolation`` set to ``None``, the parser would simply return |
| 397 |
``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and |
| 398 |
``%(home_dir)s/lumberjack`` as the value of ``my_dir``. |
| 399 |
|
| 400 |
.. index:: single: $ (dollar); interpolation in configuration files |
| 401 |
|
| 402 |
.. class:: ExtendedInterpolation() |
| 403 |
|
| 404 |
An alternative handler for interpolation which implements a more advanced |
| 405 |
syntax, used for instance in ``zc.buildout``. Extended interpolation is |
| 406 |
using ``${section:option}`` to denote a value from a foreign section. |
| 407 |
Interpolation can span multiple levels. For convenience, if the |
| 408 |
``section:`` part is omitted, interpolation defaults to the current section |
| 409 |
(and possibly the default values from the special section). |
| 410 |
|
| 411 |
For example, the configuration specified above with basic interpolation, |
| 412 |
would look like this with extended interpolation: |
| 413 |
|
| 414 |
.. code-block:: ini |
| 415 |
|
| 416 |
[Paths] |
| 417 |
home_dir: /Users |
| 418 |
my_dir: ${home_dir}/lumberjack |
| 419 |
my_pictures: ${my_dir}/Pictures |
| 420 |
|
| 421 |
[Escape] |
| 422 |
# use a $$ to escape the $ sign ($ is the only character that needs to be escaped): |
| 423 |
cost: $$80 |
| 424 |
|
| 425 |
Values from other sections can be fetched as well: |
| 426 |
|
| 427 |
.. code-block:: ini |
| 428 |
|
| 429 |
[Common] |
| 430 |
home_dir: /Users |
| 431 |
library_dir: /Library |
| 432 |
system_dir: /System |
| 433 |
macports_dir: /opt/local |
| 434 |
|
| 435 |
[Frameworks] |
| 436 |
Python: 3.2 |
| 437 |
path: ${Common:system_dir}/Library/Frameworks/ |
| 438 |
|
| 439 |
[Arthur] |
| 440 |
nickname: Two Sheds |
| 441 |
last_name: Jackson |
| 442 |
my_dir: ${Common:home_dir}/twosheds |
| 443 |
my_pictures: ${my_dir}/Pictures |
| 444 |
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} |
| 445 |
|
| 446 |
Mapping Protocol Access |
| 447 |
----------------------- |
| 448 |
|
| 449 |
.. versionadded:: 3.2 |
| 450 |
|
| 451 |
Mapping protocol access is a generic name for functionality that enables using |
| 452 |
custom objects as if they were dictionaries. In case of :mod:`!configparser`, |
| 453 |
the mapping interface implementation is using the |
| 454 |
``parser['section']['option']`` notation. |
| 455 |
|
| 456 |
``parser['section']`` in particular returns a proxy for the section's data in |
| 457 |
the parser. This means that the values are not copied but they are taken from |
| 458 |
the original parser on demand. What's even more important is that when values |
| 459 |
are changed on a section proxy, they are actually mutated in the original |
| 460 |
parser. |
| 461 |
|
| 462 |
:mod:`!configparser` objects behave as close to actual dictionaries as possible. |
| 463 |
The mapping interface is complete and adheres to the |
| 464 |
:class:`~collections.abc.MutableMapping` ABC. |
| 465 |
However, there are a few differences that should be taken into account: |
| 466 |
|
| 467 |
* By default, all keys in sections are accessible in a case-insensitive manner |
| 468 |
[1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed |
| 469 |
option key names. This means lowercased keys by default. At the same time, |
| 470 |
for a section that holds the key ``'a'``, both expressions return ``True``:: |
| 471 |
|
| 472 |
"a" in parser["section"] |
| 473 |
"A" in parser["section"] |
| 474 |
|
| 475 |
* All sections include ``DEFAULTSECT`` values as well which means that |
| 476 |
``.clear()`` on a section may not leave the section visibly empty. This is |
| 477 |
because default values cannot be deleted from the section (because technically |
| 478 |
they are not there). If they are overridden in the section, deleting causes |
| 479 |
the default value to be visible again. Trying to delete a default value |
| 480 |
causes a :exc:`KeyError`. |
| 481 |
|
| 482 |
* ``DEFAULTSECT`` cannot be removed from the parser: |
| 483 |
|
| 484 |
* trying to delete it raises :exc:`ValueError`, |
| 485 |
|
| 486 |
* ``parser.clear()`` leaves it intact, |
| 487 |
|
| 488 |
* ``parser.popitem()`` never returns it. |
| 489 |
|
| 490 |
* ``parser.get(section, option, **kwargs)`` - the second argument is **not** |
| 491 |
a fallback value. Note however that the section-level ``get()`` methods are |
| 492 |
compatible both with the mapping protocol and the classic configparser API. |
| 493 |
|
| 494 |
* ``parser.items()`` is compatible with the mapping protocol (returns a list of |
| 495 |
*section_name*, *section_proxy* pairs including the DEFAULTSECT). However, |
| 496 |
this method can also be invoked with arguments: ``parser.items(section, raw, |
| 497 |
vars)``. The latter call returns a list of *option*, *value* pairs for |
| 498 |
a specified ``section``, with all interpolations expanded (unless |
| 499 |
``raw=True`` is provided). |
| 500 |
|
| 501 |
The mapping protocol is implemented on top of the existing legacy API so that |
| 502 |
subclasses overriding the original interface still should have mappings working |
| 503 |
as expected. |
| 504 |
|
| 505 |
|
| 506 |
Customizing Parser Behaviour |
| 507 |
---------------------------- |
| 508 |
|
| 509 |
There are nearly as many INI format variants as there are applications using it. |
| 510 |
:mod:`!configparser` goes a long way to provide support for the largest sensible |
| 511 |
set of INI styles available. The default functionality is mainly dictated by |
| 512 |
historical background and it's very likely that you will want to customize some |
| 513 |
of the features. |
| 514 |
|
| 515 |
The most common way to change the way a specific config parser works is to use |
| 516 |
the :meth:`!__init__` options: |
| 517 |
|
| 518 |
* *defaults*, default value: ``None`` |
| 519 |
|
| 520 |
This option accepts a dictionary of key-value pairs which will be initially |
| 521 |
put in the ``DEFAULT`` section. This makes for an elegant way to support |
| 522 |
concise configuration files that don't specify values which are the same as |
| 523 |
the documented default. |
| 524 |
|
| 525 |
Hint: if you want to specify default values for a specific section, use |
| 526 |
:meth:`~ConfigParser.read_dict` before you read the actual file. |
| 527 |
|
| 528 |
* *dict_type*, default value: :class:`dict` |
| 529 |
|
| 530 |
This option has a major impact on how the mapping protocol will behave and how |
| 531 |
the written configuration files look. With the standard dictionary, every |
| 532 |
section is stored in the order they were added to the parser. Same goes for |
| 533 |
options within sections. |
| 534 |
|
| 535 |
An alternative dictionary type can be used for example to sort sections and |
| 536 |
options on write-back. |
| 537 |
|
| 538 |
Please note: there are ways to add a set of key-value pairs in a single |
| 539 |
operation. When you use a regular dictionary in those operations, the order |
| 540 |
of the keys will be ordered. For example: |
| 541 |
|
| 542 |
.. doctest:: |
| 543 |
|
| 544 |
>>> parser = configparser.ConfigParser() |
| 545 |
>>> parser.read_dict({'section1': {'key1': 'value1', |
| 546 |
... 'key2': 'value2', |
| 547 |
... 'key3': 'value3'}, |
| 548 |
... 'section2': {'keyA': 'valueA', |
| 549 |
... 'keyB': 'valueB', |
| 550 |
... 'keyC': 'valueC'}, |
| 551 |
... 'section3': {'foo': 'x', |
| 552 |
... 'bar': 'y', |
| 553 |
... 'baz': 'z'} |
| 554 |
... }) |
| 555 |
>>> parser.sections() |
| 556 |
['section1', 'section2', 'section3'] |
| 557 |
>>> [option for option in parser['section3']] |
| 558 |
['foo', 'bar', 'baz'] |
| 559 |
|
| 560 |
* *allow_no_value*, default value: ``False`` |
| 561 |
|
| 562 |
Some configuration files are known to include settings without values, but |
| 563 |
which otherwise conform to the syntax supported by :mod:`!configparser`. The |
| 564 |
*allow_no_value* parameter to the constructor can be used to |
| 565 |
indicate that such values should be accepted: |
| 566 |
|
| 567 |
.. doctest:: |
| 568 |
|
| 569 |
>>> import configparser |
| 570 |
|
| 571 |
>>> sample_config = """ |
| 572 |
... [mysqld] |
| 573 |
... user = mysql |
| 574 |
... pid-file = /var/run/mysqld/mysqld.pid |
| 575 |
... skip-external-locking |
| 576 |
... old_passwords = 1 |
| 577 |
... skip-bdb |
| 578 |
... # we don't need ACID today |
| 579 |
... skip-innodb |
| 580 |
... """ |
| 581 |
>>> config = configparser.ConfigParser(allow_no_value=True) |
| 582 |
>>> config.read_string(sample_config) |
| 583 |
|
| 584 |
>>> # Settings with values are treated as before: |
| 585 |
>>> config["mysqld"]["user"] |
| 586 |
'mysql' |
| 587 |
|
| 588 |
>>> # Settings without values provide None: |
| 589 |
>>> config["mysqld"]["skip-bdb"] |
| 590 |
|
| 591 |
>>> # Settings which aren't specified still raise an error: |
| 592 |
>>> config["mysqld"]["does-not-exist"] |
| 593 |
Traceback (most recent call last): |
| 594 |
... |
| 595 |
KeyError: 'does-not-exist' |
| 596 |
|
| 597 |
* *delimiters*, default value: ``('=', ':')`` |
| 598 |
|
| 599 |
Delimiters are substrings that delimit keys from values within a section. |
| 600 |
The first occurrence of a delimiting substring on a line is considered |
| 601 |
a delimiter. This means values (but not keys) can contain the delimiters. |
| 602 |
|
| 603 |
See also the *space_around_delimiters* argument to |
| 604 |
:meth:`ConfigParser.write`. |
| 605 |
|
| 606 |
* *comment_prefixes*, default value: ``('#', ';')`` |
| 607 |
|
| 608 |
* *inline_comment_prefixes*, default value: ``None`` |
| 609 |
|
| 610 |
Comment prefixes are strings that indicate the start of a valid comment within |
| 611 |
a config file. *comment_prefixes* are used only on otherwise empty lines |
| 612 |
(optionally indented) whereas *inline_comment_prefixes* can be used after |
| 613 |
every valid value (e.g. section names, options and empty lines as well). By |
| 614 |
default inline comments are disabled and ``'#'`` and ``';'`` are used as |
| 615 |
prefixes for whole line comments. |
| 616 |
|
| 617 |
.. versionchanged:: 3.2 |
| 618 |
In previous versions of :mod:`!configparser` behaviour matched |
| 619 |
``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``. |
| 620 |
|
| 621 |
Please note that config parsers don't support escaping of comment prefixes so |
| 622 |
using *inline_comment_prefixes* may prevent users from specifying option |
| 623 |
values with characters used as comment prefixes. When in doubt, avoid |
| 624 |
setting *inline_comment_prefixes*. In any circumstances, the only way of |
| 625 |
storing comment prefix characters at the beginning of a line in multiline |
| 626 |
values is to interpolate the prefix, for example:: |
| 627 |
|
| 628 |
>>> from configparser import ConfigParser, ExtendedInterpolation |
| 629 |
>>> parser = ConfigParser(interpolation=ExtendedInterpolation()) |
| 630 |
>>> # the default BasicInterpolation could be used as well |
| 631 |
>>> parser.read_string(""" |
| 632 |
... [DEFAULT] |
| 633 |
... hash = # |
| 634 |
... |
| 635 |
... [hashes] |
| 636 |
... shebang = |
| 637 |
... ${hash}!/usr/bin/env python |
| 638 |
... ${hash} -*- coding: utf-8 -*- |
| 639 |
... |
| 640 |
... extensions = |
| 641 |
... enabled_extension |
| 642 |
... another_extension |
| 643 |
... #disabled_by_comment |
| 644 |
... yet_another_extension |
| 645 |
... |
| 646 |
... interpolation not necessary = if # is not at line start |
| 647 |
... even in multiline values = line #1 |
| 648 |
... line #2 |
| 649 |
... line #3 |
| 650 |
... """) |
| 651 |
>>> print(parser['hashes']['shebang']) |
| 652 |
<BLANKLINE> |
| 653 |
#!/usr/bin/env python |
| 654 |
# -*- coding: utf-8 -*- |
| 655 |
>>> print(parser['hashes']['extensions']) |
| 656 |
<BLANKLINE> |
| 657 |
enabled_extension |
| 658 |
another_extension |
| 659 |
yet_another_extension |
| 660 |
>>> print(parser['hashes']['interpolation not necessary']) |
| 661 |
if # is not at line start |
| 662 |
>>> print(parser['hashes']['even in multiline values']) |
| 663 |
line #1 |
| 664 |
line #2 |
| 665 |
line #3 |
| 666 |
|
| 667 |
* *strict*, default value: ``True`` |
| 668 |
|
| 669 |
When set to ``True``, the parser will not allow for any section or option |
| 670 |
duplicates while reading from a single source (using :meth:`~ConfigParser.read_file`, |
| 671 |
:meth:`~ConfigParser.read_string` or :meth:`~ConfigParser.read_dict`). It is recommended to use strict |
| 672 |
parsers in new applications. |
| 673 |
|
| 674 |
.. versionchanged:: 3.2 |
| 675 |
In previous versions of :mod:`!configparser` behaviour matched |
| 676 |
``strict=False``. |
| 677 |
|
| 678 |
* *empty_lines_in_values*, default value: ``True`` |
| 679 |
|
| 680 |
In config parsers, values can span multiple lines as long as they are |
| 681 |
indented more than the key that holds them. By default parsers also let |
| 682 |
empty lines to be parts of values. At the same time, keys can be arbitrarily |
| 683 |
indented themselves to improve readability. In consequence, when |
| 684 |
configuration files get big and complex, it is easy for the user to lose |
| 685 |
track of the file structure. Take for instance: |
| 686 |
|
| 687 |
.. code-block:: ini |
| 688 |
|
| 689 |
[Section] |
| 690 |
key = multiline |
| 691 |
value with a gotcha |
| 692 |
|
| 693 |
this = is still a part of the multiline value of 'key' |
| 694 |
|
| 695 |
This can be especially problematic for the user to see if she's using a |
| 696 |
proportional font to edit the file. That is why when your application does |
| 697 |
not need values with empty lines, you should consider disallowing them. This |
| 698 |
will make empty lines split keys every time. In the example above, it would |
| 699 |
produce two keys, ``key`` and ``this``. |
| 700 |
|
| 701 |
* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is: |
| 702 |
``"DEFAULT"``) |
| 703 |
|
| 704 |
The convention of allowing a special section of default values for other |
| 705 |
sections or interpolation purposes is a powerful concept of this library, |
| 706 |
letting users create complex declarative configurations. This section is |
| 707 |
normally called ``"DEFAULT"`` but this can be customized to point to any |
| 708 |
other valid section name. Some typical values include: ``"general"`` or |
| 709 |
``"common"``. The name provided is used for recognizing default sections |
| 710 |
when reading from any source and is used when writing configuration back to |
| 711 |
a file. Its current value can be retrieved using the |
| 712 |
``parser_instance.default_section`` attribute and may be modified at runtime |
| 713 |
(i.e. to convert files from one format to another). |
| 714 |
|
| 715 |
* *interpolation*, default value: ``configparser.BasicInterpolation`` |
| 716 |
|
| 717 |
Interpolation behaviour may be customized by providing a custom handler |
| 718 |
through the *interpolation* argument. ``None`` can be used to turn off |
| 719 |
interpolation completely, ``ExtendedInterpolation()`` provides a more |
| 720 |
advanced variant inspired by ``zc.buildout``. More on the subject in the |
| 721 |
`dedicated documentation section <#interpolation-of-values>`_. |
| 722 |
:class:`RawConfigParser` has a default value of ``None``. |
| 723 |
|
| 724 |
* *converters*, default value: not set |
| 725 |
|
| 726 |
Config parsers provide option value getters that perform type conversion. By |
| 727 |
default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and |
| 728 |
:meth:`~ConfigParser.getboolean` are implemented. Should other getters be |
| 729 |
desirable, users may define them in a subclass or pass a dictionary where each |
| 730 |
key is a name of the converter and each value is a callable implementing said |
| 731 |
conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add |
| 732 |
:meth:`!getdecimal` on both the parser object and all section proxies. In |
| 733 |
other words, it will be possible to write both |
| 734 |
``parser_instance.getdecimal('section', 'key', fallback=0)`` and |
| 735 |
``parser_instance['section'].getdecimal('key', 0)``. |
| 736 |
|
| 737 |
If the converter needs to access the state of the parser, it can be |
| 738 |
implemented as a method on a config parser subclass. If the name of this |
| 739 |
method starts with ``get``, it will be available on all section proxies, in |
| 740 |
the dict-compatible form (see the ``getdecimal()`` example above). |
| 741 |
|
| 742 |
More advanced customization may be achieved by overriding default values of |
| 743 |
these parser attributes. The defaults are defined on the classes, so they may |
| 744 |
be overridden by subclasses or by attribute assignment. |
| 745 |
|
| 746 |
.. attribute:: ConfigParser.BOOLEAN_STATES |
| 747 |
|
| 748 |
By default when using :meth:`~ConfigParser.getboolean`, config parsers |
| 749 |
consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``, |
| 750 |
``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``, |
| 751 |
``'off'``. You can override this by specifying a custom dictionary of strings |
| 752 |
and their Boolean outcomes. For example: |
| 753 |
|
| 754 |
.. doctest:: |
| 755 |
|
| 756 |
>>> custom = configparser.ConfigParser() |
| 757 |
>>> custom['section1'] = {'funky': 'nope'} |
| 758 |
>>> custom['section1'].getboolean('funky') |
| 759 |
Traceback (most recent call last): |
| 760 |
... |
| 761 |
ValueError: Not a boolean: nope |
| 762 |
>>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False} |
| 763 |
>>> custom['section1'].getboolean('funky') |
| 764 |
False |
| 765 |
|
| 766 |
Other typical Boolean pairs include ``accept``/``reject`` or |
| 767 |
``enabled``/``disabled``. |
| 768 |
|
| 769 |
.. method:: ConfigParser.optionxform(option) |
| 770 |
:noindex: |
| 771 |
|
| 772 |
This method transforms option names on every read, get, or set |
| 773 |
operation. The default converts the name to lowercase. This also |
| 774 |
means that when a configuration file gets written, all keys will be |
| 775 |
lowercase. Override this method if that's unsuitable. |
| 776 |
For example: |
| 777 |
|
| 778 |
.. doctest:: |
| 779 |
|
| 780 |
>>> config = """ |
| 781 |
... [Section1] |
| 782 |
... Key = Value |
| 783 |
... |
| 784 |
... [Section2] |
| 785 |
... AnotherKey = Value |
| 786 |
... """ |
| 787 |
>>> typical = configparser.ConfigParser() |
| 788 |
>>> typical.read_string(config) |
| 789 |
>>> list(typical['Section1'].keys()) |
| 790 |
['key'] |
| 791 |
>>> list(typical['Section2'].keys()) |
| 792 |
['anotherkey'] |
| 793 |
>>> custom = configparser.RawConfigParser() |
| 794 |
>>> custom.optionxform = lambda option: option |
| 795 |
>>> custom.read_string(config) |
| 796 |
>>> list(custom['Section1'].keys()) |
| 797 |
['Key'] |
| 798 |
>>> list(custom['Section2'].keys()) |
| 799 |
['AnotherKey'] |
| 800 |
|
| 801 |
.. note:: |
| 802 |
The optionxform function transforms option names to a canonical form. |
| 803 |
This should be an idempotent function: if the name is already in |
| 804 |
canonical form, it should be returned unchanged. |
| 805 |
|
| 806 |
|
| 807 |
.. attribute:: ConfigParser.SECTCRE |
| 808 |
|
| 809 |
A compiled regular expression used to parse section headers. The default |
| 810 |
matches ``[section]`` to the name ``"section"``. Whitespace is considered |
| 811 |
part of the section name, thus ``[ larch ]`` will be read as a section of |
| 812 |
name ``" larch "``. Override this attribute if that's unsuitable. For |
| 813 |
example: |
| 814 |
|
| 815 |
.. doctest:: |
| 816 |
|
| 817 |
>>> import re |
| 818 |
>>> config = """ |
| 819 |
... [Section 1] |
| 820 |
... option = value |
| 821 |
... |
| 822 |
... [ Section 2 ] |
| 823 |
... another = val |
| 824 |
... """ |
| 825 |
>>> typical = configparser.ConfigParser() |
| 826 |
>>> typical.read_string(config) |
| 827 |
>>> typical.sections() |
| 828 |
['Section 1', ' Section 2 '] |
| 829 |
>>> custom = configparser.ConfigParser() |
| 830 |
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") |
| 831 |
>>> custom.read_string(config) |
| 832 |
>>> custom.sections() |
| 833 |
['Section 1', 'Section 2'] |
| 834 |
|
| 835 |
.. note:: |
| 836 |
|
| 837 |
While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing |
| 838 |
option lines, it's not recommended to override it because that would |
| 839 |
interfere with constructor options *allow_no_value* and *delimiters*. |
| 840 |
|
| 841 |
|
| 842 |
Legacy API Examples |
| 843 |
------------------- |
| 844 |
|
| 845 |
Mainly because of backwards compatibility concerns, :mod:`!configparser` |
| 846 |
provides also a legacy API with explicit ``get``/``set`` methods. While there |
| 847 |
are valid use cases for the methods outlined below, mapping protocol access is |
| 848 |
preferred for new projects. The legacy API is at times more advanced, |
| 849 |
low-level and downright counterintuitive. |
| 850 |
|
| 851 |
An example of writing to a configuration file:: |
| 852 |
|
| 853 |
import configparser |
| 854 |
|
| 855 |
config = configparser.RawConfigParser() |
| 856 |
|
| 857 |
# Please note that using RawConfigParser's set functions, you can assign |
| 858 |
# non-string values to keys internally, but will receive an error when |
| 859 |
# attempting to write to a file or when you get it in non-raw mode. Setting |
| 860 |
# values using the mapping protocol or ConfigParser's set() does not allow |
| 861 |
# such assignments to take place. |
| 862 |
config.add_section('Section1') |
| 863 |
config.set('Section1', 'an_int', '15') |
| 864 |
config.set('Section1', 'a_bool', 'true') |
| 865 |
config.set('Section1', 'a_float', '3.1415') |
| 866 |
config.set('Section1', 'baz', 'fun') |
| 867 |
config.set('Section1', 'bar', 'Python') |
| 868 |
config.set('Section1', 'foo', '%(bar)s is %(baz)s!') |
| 869 |
|
| 870 |
# Writing our configuration file to 'example.cfg' |
| 871 |
with open('example.cfg', 'w') as configfile: |
| 872 |
config.write(configfile) |
| 873 |
|
| 874 |
An example of reading the configuration file again:: |
| 875 |
|
| 876 |
import configparser |
| 877 |
|
| 878 |
config = configparser.RawConfigParser() |
| 879 |
config.read('example.cfg') |
| 880 |
|
| 881 |
# getfloat() raises an exception if the value is not a float |
| 882 |
# getint() and getboolean() also do this for their respective types |
| 883 |
a_float = config.getfloat('Section1', 'a_float') |
| 884 |
an_int = config.getint('Section1', 'an_int') |
| 885 |
print(a_float + an_int) |
| 886 |
|
| 887 |
# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. |
| 888 |
# This is because we are using a RawConfigParser(). |
| 889 |
if config.getboolean('Section1', 'a_bool'): |
| 890 |
print(config.get('Section1', 'foo')) |
| 891 |
|
| 892 |
To get interpolation, use :class:`ConfigParser`:: |
| 893 |
|
| 894 |
import configparser |
| 895 |
|
| 896 |
cfg = configparser.ConfigParser() |
| 897 |
cfg.read('example.cfg') |
| 898 |
|
| 899 |
# Set the optional *raw* argument of get() to True if you wish to disable |
| 900 |
# interpolation in a single get operation. |
| 901 |
print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!" |
| 902 |
print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!" |
| 903 |
|
| 904 |
# The optional *vars* argument is a dict with members that will take |
| 905 |
# precedence in interpolation. |
| 906 |
print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation', |
| 907 |
'baz': 'evil'})) |
| 908 |
|
| 909 |
# The optional *fallback* argument can be used to provide a fallback value |
| 910 |
print(cfg.get('Section1', 'foo')) |
| 911 |
# -> "Python is fun!" |
| 912 |
|
| 913 |
print(cfg.get('Section1', 'foo', fallback='Monty is not.')) |
| 914 |
# -> "Python is fun!" |
| 915 |
|
| 916 |
print(cfg.get('Section1', 'monster', fallback='No such things as monsters.')) |
| 917 |
# -> "No such things as monsters." |
| 918 |
|
| 919 |
# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError |
| 920 |
# but we can also use: |
| 921 |
|
| 922 |
print(cfg.get('Section1', 'monster', fallback=None)) |
| 923 |
# -> None |
| 924 |
|
| 925 |
Default values are available in both types of ConfigParsers. They are used in |
| 926 |
interpolation if an option used is not defined elsewhere. :: |
| 927 |
|
| 928 |
import configparser |
| 929 |
|
| 930 |
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each |
| 931 |
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'}) |
| 932 |
config.read('example.cfg') |
| 933 |
|
| 934 |
print(config.get('Section1', 'foo')) # -> "Python is fun!" |
| 935 |
config.remove_option('Section1', 'bar') |
| 936 |
config.remove_option('Section1', 'baz') |
| 937 |
print(config.get('Section1', 'foo')) # -> "Life is hard!" |
| 938 |
|
| 939 |
|
| 940 |
.. _configparser-objects: |
| 941 |
|
| 942 |
ConfigParser Objects |
| 943 |
-------------------- |
| 944 |
|
| 945 |
.. class:: ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, \ |
| 946 |
delimiters=('=', ':'), comment_prefixes=('#', ';'), \ |
| 947 |
inline_comment_prefixes=None, strict=True, \ |
| 948 |
empty_lines_in_values=True, \ |
| 949 |
default_section=configparser.DEFAULTSECT, \ |
| 950 |
interpolation=BasicInterpolation(), converters={}, \ |
| 951 |
allow_unnamed_section=False) |
| 952 |
|
| 953 |
The main configuration parser. When *defaults* is given, it is initialized |
| 954 |
into the dictionary of intrinsic defaults. When *dict_type* is given, it |
| 955 |
will be used to create the dictionary objects for the list of sections, for |
| 956 |
the options within a section, and for the default values. |
| 957 |
|
| 958 |
When *delimiters* is given, it is used as the set of substrings that |
| 959 |
divide keys from values. When *comment_prefixes* is given, it will be used |
| 960 |
as the set of substrings that prefix comments in otherwise empty lines. |
| 961 |
Comments can be indented. When *inline_comment_prefixes* is given, it will |
| 962 |
be used as the set of substrings that prefix comments in non-empty lines. |
| 963 |
|
| 964 |
When *strict* is ``True`` (the default), the parser won't allow for |
| 965 |
any section or option duplicates while reading from a single source (file, |
| 966 |
string or dictionary), raising :exc:`DuplicateSectionError` or |
| 967 |
:exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False`` |
| 968 |
(default: ``True``), each empty line marks the end of an option. Otherwise, |
| 969 |
internal empty lines of a multiline option are kept as part of the value. |
| 970 |
When *allow_no_value* is ``True`` (default: ``False``), options without |
| 971 |
values are accepted; the value held for these is ``None`` and they are |
| 972 |
serialized without the trailing delimiter. |
| 973 |
|
| 974 |
When *default_section* is given, it specifies the name for the special |
| 975 |
section holding default values for other sections and interpolation purposes |
| 976 |
(normally named ``"DEFAULT"``). This value can be retrieved and changed at |
| 977 |
runtime using the ``default_section`` instance attribute. This won't |
| 978 |
re-evaluate an already parsed config file, but will be used when writing |
| 979 |
parsed settings to a new config file. |
| 980 |
|
| 981 |
Interpolation behaviour may be customized by providing a custom handler |
| 982 |
through the *interpolation* argument. ``None`` can be used to turn off |
| 983 |
interpolation completely, ``ExtendedInterpolation()`` provides a more |
| 984 |
advanced variant inspired by ``zc.buildout``. More on the subject in the |
| 985 |
`dedicated documentation section <#interpolation-of-values>`_. |
| 986 |
|
| 987 |
All option names used in interpolation will be passed through the |
| 988 |
:meth:`optionxform` method just like any other option name reference. For |
| 989 |
example, using the default implementation of :meth:`optionxform` (which |
| 990 |
converts option names to lower case), the values ``foo %(bar)s`` and ``foo |
| 991 |
%(BAR)s`` are equivalent. |
| 992 |
|
| 993 |
When *converters* is given, it should be a dictionary where each key |
| 994 |
represents the name of a type converter and each value is a callable |
| 995 |
implementing the conversion from string to the desired datatype. Every |
| 996 |
converter gets its own corresponding :meth:`!get*` method on the parser |
| 997 |
object and section proxies. |
| 998 |
|
| 999 |
When *allow_unnamed_section* is ``True`` (default: ``False``), |
| 1000 |
the first section name can be omitted. See the |
| 1001 |
`"Unnamed Sections" section <#unnamed-sections>`_. |
| 1002 |
|
| 1003 |
It is possible to read several configurations into a single |
| 1004 |
:class:`ConfigParser`, where the most recently added configuration has the |
| 1005 |
highest priority. Any conflicting keys are taken from the more recent |
| 1006 |
configuration while the previously existing keys are retained. The example |
| 1007 |
below reads in an ``override.ini`` file, which will override any conflicting |
| 1008 |
keys from the ``example.ini`` file. |
| 1009 |
|
| 1010 |
.. code-block:: ini |
| 1011 |
|
| 1012 |
[DEFAULT] |
| 1013 |
ServerAliveInterval = -1 |
| 1014 |
|
| 1015 |
.. doctest:: |
| 1016 |
|
| 1017 |
>>> config_override = configparser.ConfigParser() |
| 1018 |
>>> config_override['DEFAULT'] = {'ServerAliveInterval': '-1'} |
| 1019 |
>>> with open('override.ini', 'w') as configfile: |
| 1020 |
... config_override.write(configfile) |
| 1021 |
... |
| 1022 |
>>> config_override = configparser.ConfigParser() |
| 1023 |
>>> config_override.read(['example.ini', 'override.ini']) |
| 1024 |
['example.ini', 'override.ini'] |
| 1025 |
>>> print(config_override.get('DEFAULT', 'ServerAliveInterval')) |
| 1026 |
-1 |
| 1027 |
|
| 1028 |
.. versionchanged:: 3.1 |
| 1029 |
The default *dict_type* is :class:`collections.OrderedDict`. |
| 1030 |
|
| 1031 |
.. versionchanged:: 3.2 |
| 1032 |
*allow_no_value*, *delimiters*, *comment_prefixes*, *strict*, |
| 1033 |
*empty_lines_in_values*, *default_section* and *interpolation* were |
| 1034 |
added. |
| 1035 |
|
| 1036 |
.. versionchanged:: 3.5 |
| 1037 |
The *converters* argument was added. |
| 1038 |
|
| 1039 |
.. versionchanged:: 3.7 |
| 1040 |
The *defaults* argument is read with :meth:`read_dict`, |
| 1041 |
providing consistent behavior across the parser: non-string |
| 1042 |
keys and values are implicitly converted to strings. |
| 1043 |
|
| 1044 |
.. versionchanged:: 3.8 |
| 1045 |
The default *dict_type* is :class:`dict`, since it now preserves |
| 1046 |
insertion order. |
| 1047 |
|
| 1048 |
.. versionchanged:: 3.13 |
| 1049 |
Raise a :exc:`MultilineContinuationError` when *allow_no_value* is |
| 1050 |
``True``, and a key without a value is continued with an indented line. |
| 1051 |
|
| 1052 |
.. versionchanged:: 3.13 |
| 1053 |
The *allow_unnamed_section* argument was added. |
| 1054 |
|
| 1055 |
.. method:: defaults() |
| 1056 |
|
| 1057 |
Return a dictionary containing the instance-wide defaults. |
| 1058 |
|
| 1059 |
|
| 1060 |
.. method:: sections() |
| 1061 |
|
| 1062 |
Return a list of the sections available; the *default section* is not |
| 1063 |
included in the list. |
| 1064 |
|
| 1065 |
|
| 1066 |
.. method:: add_section(section) |
| 1067 |
|
| 1068 |
Add a section named *section* to the instance. If a section by the given |
| 1069 |
name already exists, :exc:`DuplicateSectionError` is raised. If the |
| 1070 |
*default section* name is passed, :exc:`ValueError` is raised. The name |
| 1071 |
of the section must be a string; if not, :exc:`TypeError` is raised. |
| 1072 |
|
| 1073 |
.. versionchanged:: 3.2 |
| 1074 |
Non-string section names raise :exc:`TypeError`. |
| 1075 |
|
| 1076 |
|
| 1077 |
.. method:: has_section(section) |
| 1078 |
|
| 1079 |
Indicates whether the named *section* is present in the configuration. |
| 1080 |
The *default section* is not acknowledged. |
| 1081 |
|
| 1082 |
|
| 1083 |
.. method:: options(section) |
| 1084 |
|
| 1085 |
Return a list of options available in the specified *section*. |
| 1086 |
|
| 1087 |
|
| 1088 |
.. method:: has_option(section, option) |
| 1089 |
|
| 1090 |
If the given *section* exists, and contains the given *option*, return |
| 1091 |
:const:`True`; otherwise return :const:`False`. If the specified |
| 1092 |
*section* is :const:`None` or an empty string, DEFAULT is assumed. |
| 1093 |
|
| 1094 |
|
| 1095 |
.. method:: read(filenames, encoding=None) |
| 1096 |
|
| 1097 |
Attempt to read and parse an iterable of filenames, returning a list of |
| 1098 |
filenames which were successfully parsed. |
| 1099 |
|
| 1100 |
If *filenames* is a string, a :class:`bytes` object or a |
| 1101 |
:term:`path-like object`, it is treated as |
| 1102 |
a single filename. If a file named in *filenames* cannot be opened, that |
| 1103 |
file will be ignored. This is designed so that you can specify an |
| 1104 |
iterable of potential configuration file locations (for example, the |
| 1105 |
current directory, the user's home directory, and some system-wide |
| 1106 |
directory), and all existing configuration files in the iterable will be |
| 1107 |
read. |
| 1108 |
|
| 1109 |
If none of the named files exist, the :class:`ConfigParser` |
| 1110 |
instance will contain an empty dataset. An application which requires |
| 1111 |
initial values to be loaded from a file should load the required file or |
| 1112 |
files using :meth:`read_file` before calling :meth:`read` for any |
| 1113 |
optional files:: |
| 1114 |
|
| 1115 |
import configparser, os |
| 1116 |
|
| 1117 |
config = configparser.ConfigParser() |
| 1118 |
config.read_file(open('defaults.cfg')) |
| 1119 |
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], |
| 1120 |
encoding='cp1250') |
| 1121 |
|
| 1122 |
.. versionchanged:: 3.2 |
| 1123 |
Added the *encoding* parameter. |
| 1124 |
Previously, all files were read using the default encoding for :func:`open`. |
| 1125 |
|
| 1126 |
.. versionchanged:: 3.6.1 |
| 1127 |
The *filenames* parameter accepts a :term:`path-like object`. |
| 1128 |
|
| 1129 |
.. versionchanged:: 3.7 |
| 1130 |
The *filenames* parameter accepts a :class:`bytes` object. |
| 1131 |
|
| 1132 |
|
| 1133 |
.. method:: read_file(f, source=None) |
| 1134 |
|
| 1135 |
Read and parse configuration data from *f* which must be an iterable |
| 1136 |
yielding Unicode strings (for example files opened in text mode). |
| 1137 |
|
| 1138 |
Optional argument *source* specifies the name of the file being read. If |
| 1139 |
not given and *f* has a :attr:`!name` attribute, that is used for |
| 1140 |
*source*; the default is ``'<???>'``. |
| 1141 |
|
| 1142 |
.. versionadded:: 3.2 |
| 1143 |
Replaces :meth:`!readfp`. |
| 1144 |
|
| 1145 |
.. method:: read_string(string, source='<string>') |
| 1146 |
|
| 1147 |
Parse configuration data from a string. |
| 1148 |
|
| 1149 |
Optional argument *source* specifies a context-specific name of the |
| 1150 |
string passed. If not given, ``'<string>'`` is used. This should |
| 1151 |
commonly be a filesystem path or a URL. |
| 1152 |
|
| 1153 |
.. versionadded:: 3.2 |
| 1154 |
|
| 1155 |
|
| 1156 |
.. method:: read_dict(dictionary, source='<dict>') |
| 1157 |
|
| 1158 |
Load configuration from any object that provides a dict-like ``items()`` |
| 1159 |
method. Keys are section names, values are dictionaries with keys and |
| 1160 |
values that should be present in the section. If the used dictionary |
| 1161 |
type preserves order, sections and their keys will be added in order. |
| 1162 |
Values are automatically converted to strings. |
| 1163 |
|
| 1164 |
Optional argument *source* specifies a context-specific name of the |
| 1165 |
dictionary passed. If not given, ``<dict>`` is used. |
| 1166 |
|
| 1167 |
This method can be used to copy state between parsers. |
| 1168 |
|
| 1169 |
.. versionadded:: 3.2 |
| 1170 |
|
| 1171 |
|
| 1172 |
.. method:: get(section, option, *, raw=False, vars=None[, fallback]) |
| 1173 |
|
| 1174 |
Get an *option* value for the named *section*. If *vars* is provided, it |
| 1175 |
must be a dictionary. The *option* is looked up in *vars* (if provided), |
| 1176 |
*section*, and in *DEFAULTSECT* in that order. If the key is not found |
| 1177 |
and *fallback* is provided, it is used as a fallback value. ``None`` can |
| 1178 |
be provided as a *fallback* value. |
| 1179 |
|
| 1180 |
All the ``'%'`` interpolations are expanded in the return values, unless |
| 1181 |
the *raw* argument is true. Values for interpolation keys are looked up |
| 1182 |
in the same manner as the option. |
| 1183 |
|
| 1184 |
.. versionchanged:: 3.2 |
| 1185 |
Arguments *raw*, *vars* and *fallback* are keyword only to protect |
| 1186 |
users from trying to use the third argument as the *fallback* fallback |
| 1187 |
(especially when using the mapping protocol). |
| 1188 |
|
| 1189 |
|
| 1190 |
.. method:: getint(section, option, *, raw=False, vars=None[, fallback]) |
| 1191 |
|
| 1192 |
A convenience method which coerces the *option* in the specified *section* |
| 1193 |
to an integer. See :meth:`get` for explanation of *raw*, *vars* and |
| 1194 |
*fallback*. |
| 1195 |
|
| 1196 |
|
| 1197 |
.. method:: getfloat(section, option, *, raw=False, vars=None[, fallback]) |
| 1198 |
|
| 1199 |
A convenience method which coerces the *option* in the specified *section* |
| 1200 |
to a floating-point number. See :meth:`get` for explanation of *raw*, |
| 1201 |
*vars* and *fallback*. |
| 1202 |
|
| 1203 |
|
| 1204 |
.. method:: getboolean(section, option, *, raw=False, vars=None[, fallback]) |
| 1205 |
|
| 1206 |
A convenience method which coerces the *option* in the specified *section* |
| 1207 |
to a Boolean value. Note that the accepted values for the option are |
| 1208 |
``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to |
| 1209 |
return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which |
| 1210 |
cause it to return ``False``. These string values are checked in a |
| 1211 |
case-insensitive manner. Any other value will cause it to raise |
| 1212 |
:exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and |
| 1213 |
*fallback*. |
| 1214 |
|
| 1215 |
|
| 1216 |
.. method:: items(raw=False, vars=None) |
| 1217 |
items(section, raw=False, vars=None) |
| 1218 |
|
| 1219 |
When *section* is not given, return a list of *section_name*, |
| 1220 |
*section_proxy* pairs, including DEFAULTSECT. |
| 1221 |
|
| 1222 |
Otherwise, return a list of *name*, *value* pairs for the options in the |
| 1223 |
given *section*. Optional arguments have the same meaning as for the |
| 1224 |
:meth:`get` method. |
| 1225 |
|
| 1226 |
.. versionchanged:: 3.8 |
| 1227 |
Items present in *vars* no longer appear in the result. The previous |
| 1228 |
behaviour mixed actual parser options with variables provided for |
| 1229 |
interpolation. |
| 1230 |
|
| 1231 |
|
| 1232 |
.. method:: set(section, option, value) |
| 1233 |
|
| 1234 |
If the given section exists, set the given option to the specified value; |
| 1235 |
otherwise raise :exc:`NoSectionError`. *option* and *value* must be |
| 1236 |
strings; if not, :exc:`TypeError` is raised. |
| 1237 |
|
| 1238 |
|
| 1239 |
.. method:: write(fileobject, space_around_delimiters=True) |
| 1240 |
|
| 1241 |
Write a representation of the configuration to the specified :term:`file |
| 1242 |
object`, which must be opened in text mode (accepting strings). This |
| 1243 |
representation can be parsed by a future :meth:`read` call. If |
| 1244 |
*space_around_delimiters* is true, delimiters between |
| 1245 |
keys and values are surrounded by spaces. |
| 1246 |
|
| 1247 |
.. versionchanged:: 3.14 |
| 1248 |
Raises InvalidWriteError if this would write a representation which cannot |
| 1249 |
be accurately parsed by a future :meth:`read` call from this parser. |
| 1250 |
|
| 1251 |
.. note:: |
| 1252 |
|
| 1253 |
Comments in the original configuration file are not preserved when |
| 1254 |
writing the configuration back. |
| 1255 |
What is considered a comment, depends on the given values for |
| 1256 |
*comment_prefix* and *inline_comment_prefix*. |
| 1257 |
|
| 1258 |
|
| 1259 |
.. method:: remove_option(section, option) |
| 1260 |
|
| 1261 |
Remove the specified *option* from the specified *section*. If the |
| 1262 |
section does not exist, raise :exc:`NoSectionError`. If the option |
| 1263 |
existed to be removed, return :const:`True`; otherwise return |
| 1264 |
:const:`False`. |
| 1265 |
|
| 1266 |
|
| 1267 |
.. method:: remove_section(section) |
| 1268 |
|
| 1269 |
Remove the specified *section* from the configuration. If the section in |
| 1270 |
fact existed, return ``True``. Otherwise return ``False``. |
| 1271 |
|
| 1272 |
|
| 1273 |
.. method:: optionxform(option) |
| 1274 |
|
| 1275 |
Transforms the option name *option* as found in an input file or as passed |
| 1276 |
in by client code to the form that should be used in the internal |
| 1277 |
structures. The default implementation returns a lower-case version of |
| 1278 |
*option*; subclasses may override this or client code can set an attribute |
| 1279 |
of this name on instances to affect this behavior. |
| 1280 |
|
| 1281 |
You don't need to subclass the parser to use this method, you can also |
| 1282 |
set it on an instance, to a function that takes a string argument and |
| 1283 |
returns a string. Setting it to ``str``, for example, would make option |
| 1284 |
names case sensitive:: |
| 1285 |
|
| 1286 |
cfgparser = ConfigParser() |
| 1287 |
cfgparser.optionxform = str |
| 1288 |
|
| 1289 |
Note that when reading configuration files, whitespace around the option |
| 1290 |
names is stripped before :meth:`optionxform` is called. |
| 1291 |
|
| 1292 |
|
| 1293 |
.. data:: UNNAMED_SECTION |
| 1294 |
|
| 1295 |
A special object representing a section name used to reference the unnamed section (see :ref:`unnamed-sections`). |
| 1296 |
|
| 1297 |
|
| 1298 |
.. data:: MAX_INTERPOLATION_DEPTH |
| 1299 |
|
| 1300 |
The maximum depth for recursive interpolation for :meth:`~configparser.ConfigParser.get` when the *raw* |
| 1301 |
parameter is false. This is relevant only when the default *interpolation* |
| 1302 |
is used. |
| 1303 |
|
| 1304 |
|
| 1305 |
.. _rawconfigparser-objects: |
| 1306 |
|
| 1307 |
RawConfigParser Objects |
| 1308 |
----------------------- |
| 1309 |
|
| 1310 |
.. class:: RawConfigParser(defaults=None, dict_type=dict, \ |
| 1311 |
allow_no_value=False, *, delimiters=('=', ':'), \ |
| 1312 |
comment_prefixes=('#', ';'), \ |
| 1313 |
inline_comment_prefixes=None, strict=True, \ |
| 1314 |
empty_lines_in_values=True, \ |
| 1315 |
default_section=configparser.DEFAULTSECT, \ |
| 1316 |
interpolation=BasicInterpolation(), converters={}, \ |
| 1317 |
allow_unnamed_section=False) |
| 1318 |
|
| 1319 |
Legacy variant of the :class:`ConfigParser`. It has interpolation |
| 1320 |
disabled by default and allows for non-string section names, option |
| 1321 |
names, and values via its unsafe ``add_section`` and ``set`` methods, |
| 1322 |
as well as the legacy ``defaults=`` keyword argument handling. |
| 1323 |
|
| 1324 |
.. versionchanged:: 3.2 |
| 1325 |
*allow_no_value*, *delimiters*, *comment_prefixes*, *strict*, |
| 1326 |
*empty_lines_in_values*, *default_section* and *interpolation* were |
| 1327 |
added. |
| 1328 |
|
| 1329 |
.. versionchanged:: 3.5 |
| 1330 |
The *converters* argument was added. |
| 1331 |
|
| 1332 |
.. versionchanged:: 3.8 |
| 1333 |
The default *dict_type* is :class:`dict`, since it now preserves |
| 1334 |
insertion order. |
| 1335 |
|
| 1336 |
.. versionchanged:: 3.13 |
| 1337 |
The *allow_unnamed_section* argument was added. |
| 1338 |
|
| 1339 |
.. note:: |
| 1340 |
Consider using :class:`ConfigParser` instead which checks types of |
| 1341 |
the values to be stored internally. If you don't want interpolation, you |
| 1342 |
can use ``ConfigParser(interpolation=None)``. |
| 1343 |
|
| 1344 |
|
| 1345 |
.. method:: add_section(section) |
| 1346 |
|
| 1347 |
Add a section named *section* or :const:`UNNAMED_SECTION` to the instance. |
| 1348 |
|
| 1349 |
If the given section already exists, :exc:`DuplicateSectionError` is |
| 1350 |
raised. If the *default section* name is passed, :exc:`ValueError` is |
| 1351 |
raised. If :const:`UNNAMED_SECTION` is passed and support is disabled, |
| 1352 |
:exc:`UnnamedSectionDisabledError` is raised. |
| 1353 |
|
| 1354 |
Type of *section* is not checked which lets users create non-string named |
| 1355 |
sections. This behaviour is unsupported and may cause internal errors. |
| 1356 |
|
| 1357 |
.. versionchanged:: 3.14 |
| 1358 |
Added support for :const:`UNNAMED_SECTION`. |
| 1359 |
|
| 1360 |
|
| 1361 |
.. method:: set(section, option, value) |
| 1362 |
|
| 1363 |
If the given section exists, set the given option to the specified value; |
| 1364 |
otherwise raise :exc:`NoSectionError`. While it is possible to use |
| 1365 |
:class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters |
| 1366 |
set to true) for *internal* storage of non-string values, full |
| 1367 |
functionality (including interpolation and output to files) can only be |
| 1368 |
achieved using string values. |
| 1369 |
|
| 1370 |
This method lets users assign non-string values to keys internally. This |
| 1371 |
behaviour is unsupported and will cause errors when attempting to write |
| 1372 |
to a file or get it in non-raw mode. **Use the mapping protocol API** |
| 1373 |
which does not allow such assignments to take place. |
| 1374 |
|
| 1375 |
|
| 1376 |
Exceptions |
| 1377 |
---------- |
| 1378 |
|
| 1379 |
.. exception:: Error |
| 1380 |
|
| 1381 |
Base class for all other :mod:`!configparser` exceptions. |
| 1382 |
|
| 1383 |
|
| 1384 |
.. exception:: NoSectionError |
| 1385 |
|
| 1386 |
Exception raised when a specified section is not found. |
| 1387 |
|
| 1388 |
|
| 1389 |
.. exception:: DuplicateSectionError |
| 1390 |
|
| 1391 |
Exception raised if :meth:`~ConfigParser.add_section` is called with the name of a section |
| 1392 |
that is already present or in strict parsers when a section if found more |
| 1393 |
than once in a single input file, string or dictionary. |
| 1394 |
|
| 1395 |
.. versionchanged:: 3.2 |
| 1396 |
Added the optional *source* and *lineno* attributes and parameters to |
| 1397 |
:meth:`!__init__`. |
| 1398 |
|
| 1399 |
|
| 1400 |
.. exception:: DuplicateOptionError |
| 1401 |
|
| 1402 |
Exception raised by strict parsers if a single option appears twice during |
| 1403 |
reading from a single file, string or dictionary. This catches misspellings |
| 1404 |
and case sensitivity-related errors, e.g. a dictionary may have two keys |
| 1405 |
representing the same case-insensitive configuration key. |
| 1406 |
|
| 1407 |
|
| 1408 |
.. exception:: NoOptionError |
| 1409 |
|
| 1410 |
Exception raised when a specified option is not found in the specified |
| 1411 |
section. |
| 1412 |
|
| 1413 |
|
| 1414 |
.. exception:: InterpolationError |
| 1415 |
|
| 1416 |
Base class for exceptions raised when problems occur performing string |
| 1417 |
interpolation. |
| 1418 |
|
| 1419 |
|
| 1420 |
.. exception:: InterpolationDepthError |
| 1421 |
|
| 1422 |
Exception raised when string interpolation cannot be completed because the |
| 1423 |
number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of |
| 1424 |
:exc:`InterpolationError`. |
| 1425 |
|
| 1426 |
|
| 1427 |
.. exception:: InterpolationMissingOptionError |
| 1428 |
|
| 1429 |
Exception raised when an option referenced from a value does not exist. |
| 1430 |
Subclass of :exc:`InterpolationError`. |
| 1431 |
|
| 1432 |
|
| 1433 |
.. exception:: InterpolationSyntaxError |
| 1434 |
|
| 1435 |
Exception raised when the source text into which substitutions are made does |
| 1436 |
not conform to the required syntax. Subclass of :exc:`InterpolationError`. |
| 1437 |
|
| 1438 |
|
| 1439 |
.. exception:: MissingSectionHeaderError |
| 1440 |
|
| 1441 |
Exception raised when attempting to parse a file which has no section |
| 1442 |
headers. |
| 1443 |
|
| 1444 |
.. exception:: ParsingError |
| 1445 |
|
| 1446 |
Exception raised when errors occur attempting to parse a file. |
| 1447 |
|
| 1448 |
.. versionchanged:: 3.12 |
| 1449 |
The ``filename`` attribute and :meth:`!__init__` constructor argument were |
| 1450 |
removed. They have been available using the name ``source`` since 3.2. |
| 1451 |
|
| 1452 |
.. exception:: MultilineContinuationError |
| 1453 |
|
| 1454 |
Exception raised when a key without a corresponding value is continued with |
| 1455 |
an indented line. |
| 1456 |
|
| 1457 |
.. versionadded:: 3.13 |
| 1458 |
|
| 1459 |
.. exception:: UnnamedSectionDisabledError |
| 1460 |
|
| 1461 |
Exception raised when attempting to use the |
| 1462 |
:const:`UNNAMED_SECTION` without enabling it. |
| 1463 |
|
| 1464 |
.. versionadded:: 3.14 |
| 1465 |
|
| 1466 |
.. exception:: InvalidWriteError |
| 1467 |
|
| 1468 |
Exception raised when an attempted :meth:`ConfigParser.write` would not be parsed |
| 1469 |
accurately with a future :meth:`ConfigParser.read` call. |
| 1470 |
|
| 1471 |
Ex: Writing a key beginning with the :attr:`ConfigParser.SECTCRE` pattern |
| 1472 |
would parse as a section header when read. Attempting to write this will raise |
| 1473 |
this exception. |
| 1474 |
|
| 1475 |
.. versionadded:: 3.14 |
| 1476 |
|
| 1477 |
.. rubric:: Footnotes |
| 1478 |
|
| 1479 |
.. [1] Config parsers allow for heavy customization. If you are interested in |
| 1480 |
changing the behaviour outlined by the footnote reference, consult the |
| 1481 |
`Customizing Parser Behaviour`_ section. |