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