Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(195649)

Side by Side Diff: Doc/library/configparser.rst

Issue 28860: Fixed all the doctest failures in Doc/library/configparser.rst
Patch Set: Created 3 years ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 :mod:`configparser` --- Configuration file parser 1 :mod:`configparser` --- Configuration file parser
2 ================================================= 2 =================================================
3 3
4 .. module:: configparser 4 .. module:: configparser
5 :synopsis: Configuration file parser. 5 :synopsis: Configuration file parser.
6 6
7 .. moduleauthor:: Ken Manheimer <klm@zope.com> 7 .. moduleauthor:: Ken Manheimer <klm@zope.com>
8 .. moduleauthor:: Barry Warsaw <bwarsaw@python.org> 8 .. moduleauthor:: Barry Warsaw <bwarsaw@python.org>
9 .. moduleauthor:: Eric S. Raymond <esr@thyrsus.com> 9 .. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
10 .. moduleauthor:: Łukasz Langa <lukasz@langa.pl> 10 .. moduleauthor:: Łukasz Langa <lukasz@langa.pl>
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
60 60
61 [topsecret.server.com] 61 [topsecret.server.com]
62 Port = 50022 62 Port = 50022
63 ForwardX11 = no 63 ForwardX11 = no
64 64
65 The structure of INI files is described `in the following section 65 The structure of INI files is described `in the following section
66 <#supported-ini-file-structure>`_. Essentially, the file 66 <#supported-ini-file-structure>`_. Essentially, the file
67 consists of sections, each of which contains keys with values. 67 consists of sections, each of which contains keys with values.
68 :mod:`configparser` classes can read and write such files. Let's start by 68 :mod:`configparser` classes can read and write such files. Let's start by
69 creating the above configuration file programmatically. 69 creating the above configuration file programmatically.
70
71 .. testsetup::
72
73 import configparser
70 74
71 .. doctest:: 75 .. doctest::
72 76
73 >>> import configparser 77 >>> import configparser
berkerpeksag 2016/12/05 12:27:28 Can this be removed now? (since we've already impo
marco.buttu 2016/12/05 13:20:11 I think it is really important to keep it at the b
berkerpeksag 2016/12/05 13:29:56 Yes, that's a good point. I didn't notice it was t
marco.buttu 2016/12/05 17:30:41 In any case, the testsetup is not required (we can
74 >>> config = configparser.ConfigParser() 78 >>> config = configparser.ConfigParser()
75 >>> config['DEFAULT'] = {'ServerAliveInterval': '45', 79 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
76 ... 'Compression': 'yes', 80 ... 'Compression': 'yes',
77 ... 'CompressionLevel': '9'} 81 ... 'CompressionLevel': '9'}
78 >>> config['bitbucket.org'] = {} 82 >>> config['bitbucket.org'] = {}
79 >>> config['bitbucket.org']['User'] = 'hg' 83 >>> config['bitbucket.org']['User'] = 'hg'
80 >>> config['topsecret.server.com'] = {} 84 >>> config['topsecret.server.com'] = {}
81 >>> topsecret = config['topsecret.server.com'] 85 >>> topsecret = config['topsecret.server.com']
82 >>> topsecret['Port'] = '50022' # mutates the parser 86 >>> topsecret['Port'] = '50022' # mutates the parser
83 >>> topsecret['ForwardX11'] = 'no' # same here 87 >>> topsecret['ForwardX11'] = 'no' # same here
(...skipping 25 matching lines...) Expand all
109 False 113 False
110 >>> config['bitbucket.org']['User'] 114 >>> config['bitbucket.org']['User']
111 'hg' 115 'hg'
112 >>> config['DEFAULT']['Compression'] 116 >>> config['DEFAULT']['Compression']
113 'yes' 117 'yes'
114 >>> topsecret = config['topsecret.server.com'] 118 >>> topsecret = config['topsecret.server.com']
115 >>> topsecret['ForwardX11'] 119 >>> topsecret['ForwardX11']
116 'no' 120 'no'
117 >>> topsecret['Port'] 121 >>> topsecret['Port']
118 '50022' 122 '50022'
119 >>> for key in config['bitbucket.org']: print(key) 123 >>> for key in sorted(config['bitbucket.org']):
120 ... 124 ... print(key)
125 compression
126 compressionlevel
127 forwardx11
128 serveraliveinterval
121 user 129 user
122 compressionlevel
123 serveraliveinterval
124 compression
125 forwardx11
126 >>> config['bitbucket.org']['ForwardX11'] 130 >>> config['bitbucket.org']['ForwardX11']
127 'yes' 131 'yes'
128 132
129 As we can see above, the API is pretty straightforward. The only bit of magic 133 As we can see above, the API is pretty straightforward. The only bit of magic
130 involves the ``DEFAULT`` section which provides default values for all other 134 involves the ``DEFAULT`` section which provides default values for all other
131 sections [1]_. Note also that keys in sections are 135 sections [1]_. Note also that keys in sections are
132 case-insensitive and stored in lowercase [1]_. 136 case-insensitive and stored in lowercase [1]_.
133 137
134 138
135 Supported Datatypes 139 Supported Datatypes
(...skipping 326 matching lines...) Expand 10 before | Expand all | Expand 10 after
462 >>> parser.read_dict({'section1': {'key1': 'value1', 466 >>> parser.read_dict({'section1': {'key1': 'value1',
463 ... 'key2': 'value2', 467 ... 'key2': 'value2',
464 ... 'key3': 'value3'}, 468 ... 'key3': 'value3'},
465 ... 'section2': {'keyA': 'valueA', 469 ... 'section2': {'keyA': 'valueA',
466 ... 'keyB': 'valueB', 470 ... 'keyB': 'valueB',
467 ... 'keyC': 'valueC'}, 471 ... 'keyC': 'valueC'},
468 ... 'section3': {'foo': 'x', 472 ... 'section3': {'foo': 'x',
469 ... 'bar': 'y', 473 ... 'bar': 'y',
470 ... 'baz': 'z'} 474 ... 'baz': 'z'}
471 ... }) 475 ... })
472 >>> parser.sections() 476 >>> sorted(parser.sections())
berkerpeksag 2016/12/05 12:27:28 I'd skip this one like you did in your first patch
marco.buttu 2016/12/05 13:20:11 I agree with you, it is less readable and more con
473 ['section3', 'section2', 'section1'] 477 ['section1', 'section2', 'section3']
474 >>> [option for option in parser['section3']] 478 >>> sorted(option for option in parser['section3'])
475 ['baz', 'foo', 'bar'] 479 ['bar', 'baz', 'foo']
476 480
477 In these operations you need to use an ordered dictionary as well: 481 In these operations you need to use an ordered dictionary as well:
478 482
479 .. doctest:: 483 .. doctest::
480 484
481 >>> from collections import OrderedDict 485 >>> from collections import OrderedDict
482 >>> parser = configparser.ConfigParser() 486 >>> parser = configparser.ConfigParser()
483 >>> parser.read_dict( 487 >>> parser.read_dict(
484 ... OrderedDict(( 488 ... OrderedDict((
485 ... ('s1', 489 ... ('s1',
(...skipping 20 matching lines...) Expand all
506 ['b', 'd', 'f'] 510 ['b', 'd', 'f']
507 511
508 * *allow_no_value*, default value: ``False`` 512 * *allow_no_value*, default value: ``False``
509 513
510 Some configuration files are known to include settings without values, but 514 Some configuration files are known to include settings without values, but
511 which otherwise conform to the syntax supported by :mod:`configparser`. The 515 which otherwise conform to the syntax supported by :mod:`configparser`. The
512 *allow_no_value* parameter to the constructor can be used to 516 *allow_no_value* parameter to the constructor can be used to
513 indicate that such values should be accepted: 517 indicate that such values should be accepted:
514 518
515 .. doctest:: 519 .. doctest::
516
517 >>> import configparser
518 520
519 >>> sample_config = """ 521 >>> sample_config = """
520 ... [mysqld] 522 ... [mysqld]
521 ... user = mysql 523 ... user = mysql
522 ... pid-file = /var/run/mysqld/mysqld.pid 524 ... pid-file = /var/run/mysqld/mysqld.pid
523 ... skip-external-locking 525 ... skip-external-locking
524 ... old_passwords = 1 526 ... old_passwords = 1
525 ... skip-bdb 527 ... skip-bdb
526 ... # we don't need ACID today 528 ... # we don't need ACID today
527 ... skip-innodb 529 ... skip-innodb
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
564 566
565 .. versionchanged:: 3.2 567 .. versionchanged:: 3.2
566 In previous versions of :mod:`configparser` behaviour matched 568 In previous versions of :mod:`configparser` behaviour matched
567 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``. 569 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
568 570
569 Please note that config parsers don't support escaping of comment prefixes so 571 Please note that config parsers don't support escaping of comment prefixes so
570 using *inline_comment_prefixes* may prevent users from specifying option 572 using *inline_comment_prefixes* may prevent users from specifying option
571 values with characters used as comment prefixes. When in doubt, avoid 573 values with characters used as comment prefixes. When in doubt, avoid
572 setting *inline_comment_prefixes*. In any circumstances, the only way of 574 setting *inline_comment_prefixes*. In any circumstances, the only way of
573 storing comment prefix characters at the beginning of a line in multiline 575 storing comment prefix characters at the beginning of a line in multiline
574 values is to interpolate the prefix, for example:: 576 values is to interpolate the prefix, for example:
577
578 .. doctest::
575 579
576 >>> from configparser import ConfigParser, ExtendedInterpolation 580 >>> from configparser import ConfigParser, ExtendedInterpolation
berkerpeksag 2016/12/05 12:27:28 Perhaps we can change this example to use configpa
577 >>> parser = ConfigParser(interpolation=ExtendedInterpolation()) 581 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
578 >>> # the default BasicInterpolation could be used as well 582 >>> # the default BasicInterpolation could be used as well
579 >>> parser.read_string(""" 583 >>> parser.read_string("""
580 ... [DEFAULT] 584 ... [DEFAULT]
581 ... hash = # 585 ... hash = #
582 ... 586 ...
583 ... [hashes] 587 ... [hashes]
584 ... shebang = 588 ... shebang =
585 ... ${hash}!/usr/bin/env python 589 ... ${hash}!/usr/bin/env python
586 ... ${hash} -*- coding: utf-8 -*- 590 ... ${hash} -*- coding: utf-8 -*-
587 ... 591 ...
588 ... extensions = 592 ... extensions =
589 ... enabled_extension 593 ... enabled_extension
590 ... another_extension 594 ... another_extension
591 ... #disabled_by_comment 595 ... #disabled_by_comment
592 ... yet_another_extension 596 ... yet_another_extension
593 ... 597 ...
594 ... interpolation not necessary = if # is not at line start 598 ... interpolation not necessary = if # is not at line start
595 ... even in multiline values = line #1 599 ... even in multiline values = line #1
596 ... line #2 600 ... line #2
597 ... line #3 601 ... line #3
598 ... """) 602 ... """)
599 >>> print(parser['hashes']['shebang']) 603 >>> print(parser['hashes']['shebang'])
600 604 <BLANKLINE>
601 #!/usr/bin/env python 605 #!/usr/bin/env python
602 # -*- coding: utf-8 -*- 606 # -*- coding: utf-8 -*-
603 >>> print(parser['hashes']['extensions']) 607 >>> print(parser['hashes']['extensions'])
604 608 <BLANKLINE>
605 enabled_extension 609 enabled_extension
606 another_extension 610 another_extension
607 yet_another_extension 611 yet_another_extension
608 >>> print(parser['hashes']['interpolation not necessary']) 612 >>> print(parser['hashes']['interpolation not necessary'])
609 if # is not at line start 613 if # is not at line start
610 >>> print(parser['hashes']['even in multiline values']) 614 >>> print(parser['hashes']['even in multiline values'])
611 line #1 615 line #1
612 line #2 616 line #2
613 line #3 617 line #3
614 618
(...skipping 133 matching lines...) Expand 10 before | Expand all | Expand 10 after
748 .. attribute:: SECTCRE 752 .. attribute:: SECTCRE
749 753
750 A compiled regular expression used to parse section headers. The default 754 A compiled regular expression used to parse section headers. The default
751 matches ``[section]`` to the name ``"section"``. Whitespace is considered 755 matches ``[section]`` to the name ``"section"``. Whitespace is considered
752 part of the section name, thus ``[ larch ]`` will be read as a section of 756 part of the section name, thus ``[ larch ]`` will be read as a section of
753 name ``" larch "``. Override this attribute if that's unsuitable. For 757 name ``" larch "``. Override this attribute if that's unsuitable. For
754 example: 758 example:
755 759
756 .. doctest:: 760 .. doctest::
757 761
762 >>> import re
758 >>> config = """ 763 >>> config = """
759 ... [Section 1] 764 ... [Section 1]
760 ... option = value 765 ... option = value
761 ... 766 ...
762 ... [ Section 2 ] 767 ... [ Section 2 ]
763 ... another = val 768 ... another = val
764 ... """ 769 ... """
765 >>> typical = ConfigParser() 770 >>> typical = configparser.ConfigParser()
766 >>> typical.read_string(config) 771 >>> typical.read_string(config)
767 >>> typical.sections() 772 >>> typical.sections()
768 ['Section 1', ' Section 2 '] 773 ['Section 1', ' Section 2 ']
769 >>> custom = ConfigParser() 774 >>> custom = configparser.ConfigParser()
770 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") 775 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
771 >>> custom.read_string(config) 776 >>> custom.read_string(config)
772 >>> custom.sections() 777 >>> custom.sections()
773 ['Section 1', 'Section 2'] 778 ['Section 1', 'Section 2']
774 779
775 .. note:: 780 .. note::
776 781
777 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing 782 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
778 option lines, it's not recommended to override it because that would 783 option lines, it's not recommended to override it because that would
779 interfere with constructor options *allow_no_value* and *delimiters*. 784 interfere with constructor options *allow_no_value* and *delimiters*.
(...skipping 528 matching lines...) Expand 10 before | Expand all | Expand 10 after
1308 The ``filename`` attribute and :meth:`__init__` argument were renamed to 1313 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1309 ``source`` for consistency. 1314 ``source`` for consistency.
1310 1315
1311 1316
1312 .. rubric:: Footnotes 1317 .. rubric:: Footnotes
1313 1318
1314 .. [1] Config parsers allow for heavy customization. If you are interested in 1319 .. [1] Config parsers allow for heavy customization. If you are interested in
1315 changing the behaviour outlined by the footnote reference, consult the 1320 changing the behaviour outlined by the footnote reference, consult the
1316 `Customizing Parser Behaviour`_ section. 1321 `Customizing Parser Behaviour`_ section.
1317 1322
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+