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