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