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