blob: f661866734838fa31fc1289e1bb1baf610a89da8 [file] [log] [blame]
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00001:mod:`configparser` --- Configuration file parser
Georg Brandl116aa622007-08-15 14:28:22 +00002=================================================
3
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00004.. module:: configparser
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Configuration file parser.
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Ken Manheimer <klm@zope.com>
8.. moduleauthor:: Barry Warsaw <bwarsaw@python.org>
9.. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
Łukasz Langa26d513c2010-11-10 18:57:39 +000010.. moduleauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000011.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>
Łukasz Langa26d513c2010-11-10 18:57:39 +000012.. sectionauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl116aa622007-08-15 14:28:22 +000014.. index::
15 pair: .ini; file
16 pair: configuration; file
17 single: ini file
18 single: Windows ini file
19
Georg Brandl96a60ae2010-07-28 13:13:46 +000020This module provides the classes :class:`RawConfigParser` and
21:class:`SafeConfigParser`. They implement a basic configuration file parser
22language which provides a structure similar to what you would find in Microsoft
23Windows INI files. You can use this to write Python programs which can be
24customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Georg Brandle720c0a2009-04-27 16:20:50 +000026.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000027
Georg Brandle720c0a2009-04-27 16:20:50 +000028 This library does *not* interpret or write the value-type prefixes used in
29 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000030
Łukasz Langa26d513c2010-11-10 18:57:39 +000031.. seealso::
32
33 Module :mod:`shlex`
34 Support for a creating Unix shell-like mini-languages which can be used
35 as an alternate format for application configuration files.
36
37Quick Start
38-----------
39
40.. highlightlang:: none
41
42Let's take a very basic configuration file that looks like this::
43
44 [DEFAULT]
45 ServerAliveInterval = 45
46 Compression = yes
47 CompressionLevel = 9
48 ForwardX11 = yes
49
50 [bitbucket.org]
51 User = hg
52
53 [topsecret.server.com]
54 Port = 50022
55 ForwardX11 = no
56
57The supported file structure of INI files is described `in the following section
58<#supported-ini-file-structure>`_, fow now all there's to know is that the file
59consists of sections, each of which contains keys with values.
60:mod:`configparser` classes can read and write such files. Let's start by
61creating the above configuration file programatically.
62
63.. highlightlang:: python
64.. doctest::
65
66 >>> import configparser
67 >>> config = configparser.RawConfigParser()
68 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
69 ... 'Compression': 'yes',
70 ... 'CompressionLevel': '9'}
71 >>> config['bitbucket.org'] = {}
72 >>> config['bitbucket.org']['User'] = 'hg'
73 >>> config['topsecret.server.com'] = {}
74 >>> topsecret = config['topsecret.server.com']
75 >>> topsecret['Port'] = '50022' # mutates the parser
76 >>> topsecret['ForwardX11'] = 'no' # same here
77 >>> config['DEFAULT']['ForwardX11'] = 'yes'
78 >>> with open('example.ini', 'w') as configfile:
79 ... config.write(configfile)
80 ...
81
82As you can see, we can treat a config parser just like a dictionary. There are
83a few differences, `outlined later on <#mapping-protocol-access>`_, but the
84behaviour is very close to what you'd expect from a dictionary.
85
86Now that we've created and saved a configuration file, let's try reading it
87back and exploring the data it holds.
88
89.. highlightlang:: python
90.. doctest::
91
92 >>> import configparser
93 >>> config = configparser.RawConfigParser()
94 >>> config.sections()
95 []
96 >>> config.read('example.ini')
97 ['example.ini']
98 >>> config.sections()
99 ['bitbucket.org', 'topsecret.server.com']
100 >>> 'bitbucket.org' in config
101 True
102 >>> 'bytebong.com' in config
103 False
104 >>> config['bitbucket.org']['User']
105 'hg'
106 >>> config['DEFAULT']['Compression']
107 'yes'
108 >>> topsecret = config['topsecret.server.com']
109 >>> topsecret['ForwardX11']
110 'no'
111 >>> topsecret['Port']
112 '50022'
113 >>> for key in config['bitbucket.org']: print(key)
114 ...
115 user
116 compressionlevel
117 serveraliveinterval
118 compression
119 forwardx11
120 >>> config['bitbucket.org']['ForwardX11']
121 'yes'
122
123As we can see above, the API is pretty straight forward. The only bit of magic
124involves the ``DEFAULT`` section which provides default values for all other
125sections [customizable]_. Another thing to note is that keys in sections are
126case-insensitive so they're stored in lowercase [customizable]_.
127
128Supported Datatypes
129-------------------
130
131Config parsers do not guess datatypes of values in configuration files, always
132storing them internally as strings. This means that if you need other datatypes,
133you should convert on your own:
134
135.. highlightlang:: python
136.. doctest::
137
138 >>> int(topsecret['Port'])
139 50022
140 >>> float(topsecret['CompressionLevel'])
141 9.0
142
143Converting to the boolean type is not that simple, though. Wrapping the return
144value around ``bool()`` would do us no good since ``bool('False')`` is still
145``True``. This is why config parsers also provide :meth:`getboolean`. This handy
146method is also case insensitive and correctly recognizes boolean values from
147``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [customizable]_. An
148example of getting the boolean value:
149
150.. highlightlang:: python
151.. doctest::
152
153 >>> topsecret.getboolean('ForwardX11')
154 False
155 >>> config['bitbucket.org'].getboolean('ForwardX11')
156 True
157 >>> config.getboolean('bitbucket.org', 'Compression')
158 True
159
160Apart from :meth:`getboolean`, config parsers also provide equivalent
161:meth:`getint` and :meth:`getfloat` methods but these are far less useful
162because explicit casting is enough for these types.
163
164Fallback Values
165---------------
166
167As with a regular dictionary, you can use a section's :meth:`get` method to
168provide fallback values:
169
170.. highlightlang:: python
171.. doctest::
172
173 >>> topsecret.get('Port')
174 '50022'
175 >>> topsecret.get('CompressionLevel')
176 '9'
177 >>> topsecret.get('Cipher')
178 >>> topsecret.get('Cipher', '3des-cbc')
179 '3des-cbc'
180
181Please note that default values have precedence over fallback values. For
182instance, in our example the ``CompressionLevel`` key was specified only in the
183``DEFAULT`` section. If we try to get it from the section
184``topsecret.server.com``, we will always get the default, even if we specify
185a fallback:
186
187.. highlightlang:: python
188.. doctest::
189
190 >>> topsecret.get('CompressionLevel', '3')
191 '9'
192
193One more thing to be aware of is that the parser-level :meth:`get` method
194provides a custom, more complex interface, maintained for backwards
195compatibility. When using this method, a fallback value can be provided via the
196``fallback`` keyword-only argument:
197
198.. highlightlang:: python
199.. doctest::
200
201 >>> config.get('bitbucket.org', 'monster',
202 ... fallback='No such things as monsters')
203 'No such things as monsters'
204
205The same ``fallback`` argument can be used with the :meth:`getint`,
206:meth:`getfloat` and :meth:`getboolean` methods, for example:
207
208.. highlightlang:: python
209.. doctest::
210
211 >>> 'BatchMode' in topsecret
212 False
213 >>> topsecret.getboolean('BatchMode', fallback=True)
214 True
215 >>> config['DEFAULT']['BatchMode'] = 'no'
216 >>> topsecret.getboolean('BatchMode', fallback=True)
217 False
218
219Supported INI File Structure
220----------------------------
221
Georg Brandl96a60ae2010-07-28 13:13:46 +0000222A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000223followed by key/value entries separated by a specific string (``=`` or ``:`` by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000224default [customizable]_). By default, section names are case sensitive but keys
225are not [customizable]_. Leading und trailing whitespace is removed from keys and from values.
226Values can be omitted, in which case the key/value delimiter may also be left
227out. Values can also span multiple lines, as long as they are indented deeper
228than the first line of the value. Depending on the parser's mode, blank lines
229may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000230
231Configuration files may include comments, prefixed by specific characters (``#``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000232and ``;`` by default [customizable]_). Comments may appear on their own in an
233otherwise empty line, or may be entered in lines holding values or section
234names. In the latter case, they need to be preceded by a whitespace character
235to be recognized as a comment. (For backwards compatibility, by default only
236``;`` starts an inline comment, while ``#`` does not [customizable]_.)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000237
238On top of the core functionality, :class:`SafeConfigParser` supports
239interpolation. This means values can contain format strings which refer to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000240other values in the same section, or values in a special ``DEFAULT`` section
241[customizable]_. Additional defaults can be provided on initialization.
242
243.. highlightlang:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245For example::
246
Georg Brandl96a60ae2010-07-28 13:13:46 +0000247 [Paths]
248 home_dir: /Users
249 my_dir: %(home_dir)s/lumberjack
250 my_pictures: %(my_dir)s/Pictures
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Georg Brandl96a60ae2010-07-28 13:13:46 +0000252 [Multiline Values]
253 chorus: I'm a lumberjack, and I'm okay
254 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Georg Brandl96a60ae2010-07-28 13:13:46 +0000256 [No Values]
257 key_without_value
258 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000259
Georg Brandl96a60ae2010-07-28 13:13:46 +0000260 [You can use comments] ; after a useful line
261 ; in an empty line
262 after: a_value ; here's another comment
263 inside: a ;comment
264 multiline ;comment
265 value! ;comment
266
267 [Sections Can Be Indented]
268 can_values_be_as_well = True
269 does_that_mean_anything_special = False
270 purpose = formatting for readability
271 multiline_values = are
272 handled just fine as
273 long as they are indented
274 deeper than the first line
275 of a value
276 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000277
Georg Brandl96a60ae2010-07-28 13:13:46 +0000278In the example above, :class:`SafeConfigParser` would resolve ``%(home_dir)s``
279to the value of ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in
280effect would resolve to ``/Users/lumberjack``. All interpolations are done on
281demand so keys used in the chain of references do not have to be specified in
282any specific order in the configuration file.
283
284:class:`RawConfigParser` would simply return ``%(my_dir)s/Pictures`` as the
285value of ``my_pictures`` and ``%(home_dir)s/lumberjack`` as the value of
286``my_dir``. Other features presented in the example are handled in the same
287manner by both parsers.
288
Łukasz Langa26d513c2010-11-10 18:57:39 +0000289Mapping Protocol Access
290-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000291
Łukasz Langa26d513c2010-11-10 18:57:39 +0000292.. versionadded:: 3.2
293.. highlightlang:: python
Georg Brandl96a60ae2010-07-28 13:13:46 +0000294
Łukasz Langa26d513c2010-11-10 18:57:39 +0000295Mapping protocol access is a generic name for functionality that enables using
296custom objects as if they were dictionaries. In case of :mod:`configparser`,
297the mapping interface implementation is using the
298``parser['section']['option']`` notation.
299
300``parser['section']`` in particular returns a proxy for the section's data in
301the parser. This means that the values are not copied but they are taken from
302the original parser on demand. What's even more important is that when values
303are changed on a section proxy, they are actually mutated in the original
304parser.
305
306:mod:`configparser` objects behave as close to actual dictionaries as possible.
307The mapping interface is complete and adheres to the ``MutableMapping`` ABC.
308However, there are a few differences that should be taken into account:
309
310* by default, all keys in sections are accessible in a case-insensitive manner
311 [customizable]_. E.g. ``for option in parser["section"]`` yields only
312 ``optionxform``'ed option key names. This means lowercased keys by default.
313 At the same time, for a section that holds the key ``"a"``, both expressions
314 return ``True``::
315
316 "a" in parser["section"]
317 "A" in parser["section"]
318
319* all sections include ``DEFAULTSECT`` values as well which means that
320 ``.clear()`` on a section may not leave the section visibly empty. This is
321 because default values cannot be deleted from the section (because technically
322 they are not there). If they are overriden in the section, deleting causes the
323 default value to be visible again. Trying to delete a default value causes
324 a ``KeyError``.
325
326* trying to delete the ``DEFAULTSECT`` throws ``ValueError``
327
328* there are two parser-level methods in the legacy API that hide
329 the dictionary interface and are incompatible:
330
331 * ``parser.get(section, option, **kwargs)`` - the second argument is **not**
332 a fallback value
333
334 * ``parser.items(section)`` - this returns a list of ``(option, value)``
335 pairs for a specified ``section``.
336
337The mapping protocol is implemented on top of the existing legacy API so that
338subclassing the original interface makes the mappings work as expected as well.
339One difference is the explicit lack of support for the `__name__` special key.
340This is because the existing behaviour of `__name__` is very inconsistent and
341supporting it would only lead to problems. Details `here
342<http://mail.python.org/pipermail/python-dev/2010-July/102556.html>`_.
343
344Customizing Parser Behaviour
345----------------------------
346
347There are nearly as many INI format variants as there are applications using it.
348:mod:`configparser` goes a long way to provide support for the largest sensible
349set of INI styles available. The default functionality is mainly dictated by
350historical background and it's very likely that you will want to customize some
351of the features.
352
353The most natural way to change the way a specific config parser works is to use
354the :meth:`__init__` options:
355
356* *defaults*, default value: ``None``
357
358 This option accepts a dictionary of key-value pairs which will be initially
359 put in the ``DEFAULTSECT``. This makes for an elegant way to support concise
360 configuration files that don't specify values which are the same as the
361 documented default.
362
363 Hint: if you want to specify default values for a specific section, use the
364 :meth:`read_dict` before you read the actual file.
365
366* *dict_type*, default value: :class:`collections.OrderedDict`
367
368 This option has a major impact on how the mapping protocol will behave and how
369 the written configuration files will look like. With the default ordered
370 dictionary, every section is stored in the order they were added to the
371 parser. Same goes for options within sections.
372
373 An alternative dictionary type can be used for example to sort sections and
374 options on write-back. You can also use a regular dictionary for performance
375 reasons.
376
377 Please note: there are ways to add a set of key-value pairs in a single
378 operation. When you use a regular dictionary in those operations, the order of
379 the keys may be random. For example:
380
381 .. highlightlang:: python
382 .. doctest::
383
384 >>> parser = configparser.RawConfigParser()
385 >>> parser.read_dict({'section1': {'key1': 'value1',
386 ... 'key2': 'value2',
387 ... 'key3': 'value3'},
388 ... 'section2': {'keyA': 'valueA',
389 ... 'keyB': 'valueB',
390 ... 'keyC': 'valueC'},
391 ... 'section3': {'foo': 'x',
392 ... 'bar': 'y',
393 ... 'baz': 'z'}
394 ... })
395 >>> parser.sections()
396 ['section3', 'section2', 'section1']
397 >>> [option for option in parser['section3']]
398 ['baz', 'foo', 'bar']
399
400 In these operations you need to use an ordered dictionary as well:
401
402 .. highlightlang:: python
403 .. doctest::
404
405 >>> from collections import OrderedDict
406 >>> parser = configparser.RawConfigParser()
407 >>> parser.read_dict(
408 ... OrderedDict((
409 ... ('s1',
410 ... OrderedDict((
411 ... ('1', '2'),
412 ... ('3', '4'),
413 ... ('5', '6'),
414 ... ))
415 ... ),
416 ... ('s2',
417 ... OrderedDict((
418 ... ('a', 'b'),
419 ... ('c', 'd'),
420 ... ('e', 'f'),
421 ... ))
422 ... ),
423 ... ))
424 ... )
425 >>> parser.sections()
426 ['s1', 's2']
427 >>> [option for option in parser['s1']]
428 ['1', '3', '5']
429 >>> [option for option in parser['s2'].values()]
430 ['b', 'd', 'f']
431
432* *allow_no_value*, default value: ``False``
433
434 Some configuration files are known to include settings without values, but
435 which otherwise conform to the syntax supported by :mod:`configparser`. The
436 *allow_no_value* parameter to the :meth:`__init__` method can be used to
437 indicate that such values should be accepted:
438
439 .. highlightlang:: python
440 .. doctest::
441
442 >>> import configparser
443
444 >>> sample_config = """
445 ... [mysqld]
446 ... user = mysql
447 ... pid-file = /var/run/mysqld/mysqld.pid
448 ... skip-external-locking
449 ... old_passwords = 1
450 ... skip-bdb
451 ... skip-innodb # we don't need ACID today
452 ... """
453 >>> config = configparser.RawConfigParser(allow_no_value=True)
454 >>> config.read_string(sample_config)
455
456 >>> # Settings with values are treated as before:
457 >>> config["mysqld"]["user"]
458 'mysql'
459
460 >>> # Settings without values provide None:
461 >>> config["mysqld"]["skip-bdb"]
462
463 >>> # Settings which aren't specified still raise an error:
464 >>> config["mysqld"]["does-not-exist"]
465 Traceback (most recent call last):
466 ...
467 KeyError: 'does-not-exist'
468
469* *delimiters*, default value: ``('=', ':')``
470
471 Delimiters are substrings that delimit keys from values within a section. The
472 first occurence of a delimiting substring on a line is considered a delimiter.
473 This means values (but not keus) can contain substrings that are in the
474 *delimiters*.
475
476 See also the *space_around_delimiters* argument to
477 :meth:`RawConfigParser.write`.
478
479* *comment_prefixes*, default value: ``_COMPATIBLE`` (``'#'`` valid on empty
480 lines, ``';'`` valid also on non-empty lines)
481
482 Comment prefixes are substrings that indicate the start of a valid comment
483 within a config file. The peculiar default value allows for comments starting
484 with ``'#'`` or ``';'`` but only the latter can be used in a non-empty line.
485 This is obviously dictated by backwards compatibiliy. A more predictable
486 approach would be to specify prefixes as ``('#', ';')`` which will allow for
487 both prefixes to be used in non-empty lines.
488
489 Please note that config parsers don't support escaping of comment prefixes so
490 leaving characters out of *comment_prefixes* is a way of ensuring they can be
491 used as parts of keys or values.
492
493* *strict*, default value: ``False``
494
495 If set to ``True``, the parser will not allow for any section or option
496 duplicates while reading from a single source (using :meth:`read_file`,
497 :meth:`read_string` or :meth:`read_dict`). The default is ``False`` only
498 because of backwards compatibility reasons. It's recommended to use strict
499 parsers in new applications.
500
501* *empty_lines_in_values*, default value: ``True``
502
503 .. highlightlang:: none
504
505 In config parsers, values can be multiline as long as they're indented deeper
506 than the key that holds them. By default parsers also let empty lines to be
507 parts of values. At the same time, keys can be arbitrarily indented themselves
508 to improve readability. In consequence, when configuration files get big and
509 complex, it's easy for the user to lose track of the file structure. Take for
510 instance::
511
512 [Section]
513 key = multiline
514 value with a gotcha
515
516 this = is still a part of the multiline value of 'key'
517
518
519 This can be especially problematic for the user to see if she's using
520 a proportional font to edit the file. That's why when your application does
521 not need values with empty lines, you should consider disallowing them. This
522 will make empty lines split keys every time. In the example above, it would
523 produce two keys, ``key`` and ``this``.
524
525.. highlightlang:: python
526
527More advanced customization may be achieved by overriding default values of the
528following parser members:
529
530* `RawConfigParser.BOOLEAN_STATES`
531
532 By default when using :meth:`getboolean`, config parsers consider the
533 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
534 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You can
535 override this by specifying a custom dictionary of strings and their boolean
536 outcomes. For example:
537
538 .. highlightlang:: python
539 .. doctest::
540
541 >>> custom = configparser.RawConfigParser()
542 >>> custom['section1'] = {'funky': 'nope'}
543 >>> custom['section1'].getboolean('funky')
544 Traceback (most recent call last):
545 ...
546 ValueError: Not a boolean: nope
547 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
548 >>> custom['section1'].getboolean('funky')
549 False
550
551 Other typical boolean pairs include ``accept``/``reject`` or
552 ``enabled``/``disabled``.
553
554* :meth:`RawConfigParser.optionxform`
555
556 This is a method that transforms option names on every read or set operation.
557 By default it converts the name to lowercase. This also means that when
558 a configuration file gets written, all keys will be lowercase. If you find
559 that behaviour unsuitable, you can override this method. For example:
560
561 .. highlightlang:: python
562 .. doctest::
563
564 >>> config = """
565 ... [Section1]
566 ... Key = Value
567 ...
568 ... [Section2]
569 ... AnotherKey = Value
570 ... """
571 >>> typical = configparser.RawConfigParser()
572 >>> typical.read_string(config)
573 >>> list(typical['Section1'].keys())
574 ['key']
575 >>> list(typical['Section2'].keys())
576 ['anotherkey']
577 >>> custom = configparser.RawConfigParser()
578 >>> custom.optionxform = lambda option: option
579 >>> custom.read_string(config)
580 >>> list(custom['Section1'].keys())
581 ['Key']
582 >>> list(custom['Section2'].keys())
583 ['AnotherKey']
584
585Legacy API Examples
586-------------------
587
588Mainly because of backwards compatibility concerns, :mod:`configparser`
589provides also a legacy API with explicit ``get``/``set`` methods. While there
590are valid use cases for the methods outlined below, mapping protocol access
591is preferred for new projects. The legacy API is at times more advanced,
592low-level and downright counterintuitive.
593
594An example of writing to a configuration file::
595
596 import configparser
597
598 config = configparser.RawConfigParser()
599
600 # Please note that using RawConfigParser's and the raw mode of
601 # ConfigParser's respective set functions, you can assign non-string values
602 # to keys internally, but will receive an error when attempting to write to
603 # a file or when you get it in non-raw mode. Setting values using the
604 # mapping protocol or SafeConfigParser's set() does not allow such
605 # assignments to take place.
606 config.add_section('Section1')
607 config.set('Section1', 'int', '15')
608 config.set('Section1', 'bool', 'true')
609 config.set('Section1', 'float', '3.1415')
610 config.set('Section1', 'baz', 'fun')
611 config.set('Section1', 'bar', 'Python')
612 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
613
614 # Writing our configuration file to 'example.cfg'
615 with open('example.cfg', 'w') as configfile:
616 config.write(configfile)
617
618An example of reading the configuration file again::
619
620 import configparser
621
622 config = configparser.RawConfigParser()
623 config.read('example.cfg')
624
625 # getfloat() raises an exception if the value is not a float
626 # getint() and getboolean() also do this for their respective types
627 float = config.getfloat('Section1', 'float')
628 int = config.getint('Section1', 'int')
629 print(float + int)
630
631 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
632 # This is because we are using a RawConfigParser().
633 if config.getboolean('Section1', 'bool'):
634 print(config.get('Section1', 'foo'))
635
636To get interpolation, you will need to use a :class:`SafeConfigParser` or, if
637you absolutely have to, a :class:`ConfigParser`::
638
639 import configparser
640
641 cfg = configparser.SafeConfigParser()
642 cfg.read('example.cfg')
643
644 # Set the optional `raw` argument of get() to True if you wish to disable
645 # interpolation in a single get operation.
646 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
647 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
648
649 # The optional `vars` argument is a dict with members that will take
650 # precedence in interpolation.
651 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
652 'baz': 'evil'}))
653
654 # The optional `fallback` argument can be used to provide a fallback value
655 print(cfg.get('Section1', 'foo'))
656 # -> "Python is fun!"
657
658 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
659 # -> "Python is fun!"
660
661 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
662 # -> "No such things as monsters."
663
664 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
665 # but we can also use:
666
667 print(cfg.get('Section1', 'monster', fallback=None))
668 # -> None
669
670
671Defaults are available in all three types of ConfigParsers. They are used in
672interpolation if an option used is not defined elsewhere. ::
673
674 import configparser
675
676 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
677 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
678 config.read('example.cfg')
679
680 print(config.get('Section1', 'foo')) # -> "Python is fun!"
681 config.remove_option('Section1', 'bar')
682 config.remove_option('Section1', 'baz')
683 print(config.get('Section1', 'foo')) # -> "Life is hard!"
684
685.. _rawconfigparser-objects:
686
687RawConfigParser Objects
688-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000689
Fred Drakea4923622010-08-09 12:52:45 +0000690.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692 The basic configuration object. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000693 into the dictionary of intrinsic defaults. When *dict_type* is given, it
694 will be used to create the dictionary objects for the list of sections, for
695 the options within a section, and for the default values.
696
697 When *delimiters* is given, it will be used as the set of substrings that
698 divide keys from values. When *comment_prefixes* is given, it will be used
699 as the set of substrings that prefix comments in a line, both for the whole
700 line and inline comments. For backwards compatibility, the default value for
701 *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can
702 start whole line comments while only ``;`` can start inline comments.
703
Fred Drakea4923622010-08-09 12:52:45 +0000704 When *strict* is ``True`` (default: ``False``), the parser won't allow for
705 any section or option duplicates while reading from a single source (file,
706 string or dictionary), raising :exc:`DuplicateSectionError` or
707 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
708 (default: ``True``), each empty line marks the end of an option. Otherwise,
709 internal empty lines of a multiline option are kept as part of the value.
710 When *allow_no_value* is ``True`` (default: ``False``), options without
711 values are accepted; the value presented for these is ``None``.
Fred Drake03c44a32010-02-19 06:08:41 +0000712
Georg Brandl96a60ae2010-07-28 13:13:46 +0000713 This class does not support the magical interpolation behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000715 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000716 The default *dict_type* is :class:`collections.OrderedDict`.
717
Fred Drake03c44a32010-02-19 06:08:41 +0000718 .. versionchanged:: 3.2
Fred Drakea4923622010-08-09 12:52:45 +0000719 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
720 *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000721
Fred Drake03c44a32010-02-19 06:08:41 +0000722
Georg Brandl116aa622007-08-15 14:28:22 +0000723.. method:: RawConfigParser.defaults()
724
725 Return a dictionary containing the instance-wide defaults.
726
727
728.. method:: RawConfigParser.sections()
729
730 Return a list of the sections available; ``DEFAULT`` is not included in the
731 list.
732
733
734.. method:: RawConfigParser.add_section(section)
735
736 Add a section named *section* to the instance. If a section by the given name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000737 already exists, :exc:`DuplicateSectionError` is raised. If the name
738 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
739 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
741.. method:: RawConfigParser.has_section(section)
742
743 Indicates whether the named section is present in the configuration. The
744 ``DEFAULT`` section is not acknowledged.
745
746
747.. method:: RawConfigParser.options(section)
748
749 Returns a list of options available in the specified *section*.
750
751
752.. method:: RawConfigParser.has_option(section, option)
753
754 If the given section exists, and contains the given option, return
755 :const:`True`; otherwise return :const:`False`.
756
Georg Brandl116aa622007-08-15 14:28:22 +0000757
Georg Brandl8dcaa732010-07-29 12:17:40 +0000758.. method:: RawConfigParser.read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760 Attempt to read and parse a list of filenames, returning a list of filenames
Georg Brandl8dcaa732010-07-29 12:17:40 +0000761 which were successfully parsed. If *filenames* is a string, it is treated as
762 a single filename. If a file named in *filenames* cannot be opened, that
763 file will be ignored. This is designed so that you can specify a list of
764 potential configuration file locations (for example, the current directory,
765 the user's home directory, and some system-wide directory), and all existing
766 configuration files in the list will be read. If none of the named files
767 exist, the :class:`ConfigParser` instance will contain an empty dataset. An
768 application which requires initial values to be loaded from a file should
Florent Xiclunae3c39ae2010-08-15 20:21:26 +0000769 load the required file or files using :meth:`read_file` before calling
Georg Brandl8dcaa732010-07-29 12:17:40 +0000770 :meth:`read` for any optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000771
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000772 import configparser, os
Georg Brandl116aa622007-08-15 14:28:22 +0000773
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000774 config = configparser.ConfigParser()
Florent Xiclunae3c39ae2010-08-15 20:21:26 +0000775 config.read_file(open('defaults.cfg'))
Georg Brandl8dcaa732010-07-29 12:17:40 +0000776 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250')
777
778 .. versionadded:: 3.2
779 The *encoding* parameter. Previously, all files were read using the
780 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
Georg Brandl116aa622007-08-15 14:28:22 +0000782
Fred Drakea4923622010-08-09 12:52:45 +0000783.. method:: RawConfigParser.read_file(f, source=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000784
Fred Drakea4923622010-08-09 12:52:45 +0000785 Read and parse configuration data from the file or file-like object in *f*
Georg Brandl73753d32009-09-22 13:53:14 +0000786 (only the :meth:`readline` method is used). The file-like object must
787 operate in text mode, i.e. return strings from :meth:`readline`.
788
Fred Drakea4923622010-08-09 12:52:45 +0000789 Optional argument *source* specifies the name of the file being read. It not
790 given and *f* has a :attr:`name` attribute, that is used for *source*; the
791 default is ``<???>``.
Georg Brandl116aa622007-08-15 14:28:22 +0000792
Fred Drakea4923622010-08-09 12:52:45 +0000793 .. versionadded:: 3.2
794 Renamed from :meth:`readfp` (with the ``filename`` attribute renamed to
795 ``source`` for consistency with other ``read_*`` methods).
796
797
798.. method:: RawConfigParser.read_string(string, source='<string>')
799
800 Parse configuration data from a given string.
801
802 Optional argument *source* specifies a context-specific name of the string
803 passed. If not given, ``<string>`` is used.
804
805 .. versionadded:: 3.2
806
Georg Brandl67b21b72010-08-17 15:07:14 +0000807
Fred Drakea4923622010-08-09 12:52:45 +0000808.. method:: RawConfigParser.read_dict(dictionary, source='<dict>')
809
810 Load configuration from a dictionary. Keys are section names, values are
811 dictionaries with keys and values that should be present in the section. If
812 the used dictionary type preserves order, sections and their keys will be
Fred Drakecc645b92010-09-04 04:35:34 +0000813 added in order. Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +0000814
815 Optional argument *source* specifies a context-specific name of the
816 dictionary passed. If not given, ``<dict>`` is used.
817
818 .. versionadded:: 3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000819
Łukasz Langa26d513c2010-11-10 18:57:39 +0000820.. method:: RawConfigParser.get(section, option, [vars, fallback])
Georg Brandl67b21b72010-08-17 15:07:14 +0000821
Fred Drakecc645b92010-09-04 04:35:34 +0000822 Get an *option* value for the named *section*. If *vars* is provided, it
823 must be a dictionary. The *option* is looked up in *vars* (if provided),
824 *section*, and in *DEFAULTSECT* in that order. If the key is not found and
Łukasz Langa26d513c2010-11-10 18:57:39 +0000825 *fallback* is provided, it is used as a fallback value. ``None`` can be
826 provided as a *fallback* value.
827
828 .. versionchanged:: 3.2
829 Arguments *vars* and *fallback* are keyword only to protect users from
830 trying to use the third argument as the *fallback* fallback (especially
831 when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833
Łukasz Langa26d513c2010-11-10 18:57:39 +0000834.. method:: RawConfigParser.getint(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000835
Fred Drakecc645b92010-09-04 04:35:34 +0000836 A convenience method which coerces the *option* in the specified *section* to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000837 an integer. See :meth:`get` for explanation of *vars* and *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
839
Łukasz Langa26d513c2010-11-10 18:57:39 +0000840.. method:: RawConfigParser.getfloat(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Fred Drakecc645b92010-09-04 04:35:34 +0000842 A convenience method which coerces the *option* in the specified *section* to
843 a floating point number. See :meth:`get` for explanation of *vars* and
Łukasz Langa26d513c2010-11-10 18:57:39 +0000844 *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000845
846
Łukasz Langa26d513c2010-11-10 18:57:39 +0000847.. method:: RawConfigParser.getboolean(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000848
Fred Drakecc645b92010-09-04 04:35:34 +0000849 A convenience method which coerces the *option* in the specified *section*
850 to a Boolean value. Note that the accepted values for the option are
851 ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
852 return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
853 cause it to return ``False``. These string values are checked in
854 a case-insensitive manner. Any other value will cause it to raise
Łukasz Langa26d513c2010-11-10 18:57:39 +0000855 :exc:`ValueError`. See :meth:`get` for explanation of *vars* and *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857
858.. method:: RawConfigParser.items(section)
859
Łukasz Langa26d513c2010-11-10 18:57:39 +0000860 Return a list of ``(name, value)`` pairs for each option in the given
861 *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000862
863
864.. method:: RawConfigParser.set(section, option, value)
865
866 If the given section exists, set the given option to the specified value;
867 otherwise raise :exc:`NoSectionError`. While it is possible to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000868 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set
869 to true) for *internal* storage of non-string values, full functionality
870 (including interpolation and output to files) can only be achieved using
871 string values.
872
873.. warning::
874
875 This method lets users assign non-string values to keys internally. This
876 behaviour is unsupported and will cause errors when attempting to write to
877 a file or get it in non-raw mode. **Use the mapping protocol API** which does
878 not allow such assignments to take place.
Georg Brandl116aa622007-08-15 14:28:22 +0000879
Georg Brandl116aa622007-08-15 14:28:22 +0000880
Georg Brandl96a60ae2010-07-28 13:13:46 +0000881.. method:: RawConfigParser.write(fileobject, space_around_delimiters=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000882
Łukasz Langa26d513c2010-11-10 18:57:39 +0000883 Write a representation of the configuration to the specified
884 :term:`file object`, which must be opened in text mode (accepting strings).
885 This representation can be parsed by a future :meth:`read` call. If
886 ``space_around_delimiters`` is ``True`` (the default), delimiters between
887 keys and values are surrounded by spaces.
Georg Brandl116aa622007-08-15 14:28:22 +0000888
Georg Brandl116aa622007-08-15 14:28:22 +0000889
890.. method:: RawConfigParser.remove_option(section, option)
891
892 Remove the specified *option* from the specified *section*. If the section does
893 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
894 return :const:`True`; otherwise return :const:`False`.
895
Georg Brandl116aa622007-08-15 14:28:22 +0000896
897.. method:: RawConfigParser.remove_section(section)
898
899 Remove the specified *section* from the configuration. If the section in fact
900 existed, return ``True``. Otherwise return ``False``.
901
902
903.. method:: RawConfigParser.optionxform(option)
904
Georg Brandl495f7b52009-10-27 15:28:25 +0000905 Transforms the option name *option* as found in an input file or as passed in
906 by client code to the form that should be used in the internal structures.
907 The default implementation returns a lower-case version of *option*;
908 subclasses may override this or client code can set an attribute of this name
909 on instances to affect this behavior.
910
911 You don't necessarily need to subclass a ConfigParser to use this method, you
912 can also re-set it on an instance, to a function that takes a string
913 argument. Setting it to ``str``, for example, would make option names case
914 sensitive::
915
916 cfgparser = ConfigParser()
917 ...
918 cfgparser.optionxform = str
919
920 Note that when reading configuration files, whitespace around the
921 option names are stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Georg Brandl67b21b72010-08-17 15:07:14 +0000923
Fred Drakea4923622010-08-09 12:52:45 +0000924.. method:: RawConfigParser.readfp(fp, filename=None)
925
926 .. deprecated:: 3.2
927 Please use :meth:`read_file` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000928
Georg Brandl67b21b72010-08-17 15:07:14 +0000929
Georg Brandl116aa622007-08-15 14:28:22 +0000930.. _configparser-objects:
931
932ConfigParser Objects
933--------------------
934
Łukasz Langa26d513c2010-11-10 18:57:39 +0000935.. warning::
936 Whenever you can, consider using :class:`SafeConfigParser` which
937 adds validation and escaping for the interpolation.
938
Georg Brandl116aa622007-08-15 14:28:22 +0000939The :class:`ConfigParser` class extends some methods of the
Łukasz Langa26d513c2010-11-10 18:57:39 +0000940:class:`RawConfigParser` interface, adding some optional arguments.
941
942.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
943
944 Derived class of :class:`RawConfigParser` that implements the magical
945 interpolation feature and adds optional arguments to the :meth:`get` and
946 :meth:`items` methods.
947
948 :class:`SafeConfigParser` is generally recommended over this class if you
949 need interpolation.
950
951 The values in *defaults* must be appropriate for the ``%()s`` string
952 interpolation. Note that *__name__* is an intrinsic default; its value is
953 the section name, and will override any value provided in *defaults*.
954
955 All option names used in interpolation will be passed through the
956 :meth:`optionxform` method just like any other option name reference. For
957 example, using the default implementation of :meth:`optionxform` (which
958 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
959 %(BAR)s`` are equivalent.
960
961 .. versionchanged:: 3.1
962 The default *dict_type* is :class:`collections.OrderedDict`.
963
964 .. versionchanged:: 3.2
965 *allow_no_value*, *delimiters*, *comment_prefixes*,
966 *strict* and *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968
Łukasz Langa26d513c2010-11-10 18:57:39 +0000969.. method:: ConfigParser.get(section, option, raw=False, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000970
Georg Brandl470a1232010-07-29 14:17:12 +0000971 Get an *option* value for the named *section*. If *vars* is provided, it
972 must be a dictionary. The *option* is looked up in *vars* (if provided),
Fred Drakecc645b92010-09-04 04:35:34 +0000973 *section*, and in *DEFAULTSECT* in that order. If the key is not found and
Łukasz Langa26d513c2010-11-10 18:57:39 +0000974 *fallback* is provided, it is used as a fallback value. ``None`` can be
975 provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +0000976
977 All the ``'%'`` interpolations are expanded in the return values, unless the
978 *raw* argument is true. Values for interpolation keys are looked up in the
979 same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Łukasz Langa26d513c2010-11-10 18:57:39 +0000981 .. versionchanged:: 3.2
982 Arguments *raw*, *vars* and *fallback* are keyword only to protect users
983 from trying to use the third argument as the *fallback* fallback
984 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000985
Łukasz Langa26d513c2010-11-10 18:57:39 +0000986
987.. method:: ConfigParser.getint(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000988
989 A convenience method which coerces the *option* in the specified *section* to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000990 an integer. See :meth:`get` for explanation of *raw*, *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000991
992
Łukasz Langa26d513c2010-11-10 18:57:39 +0000993.. method:: ConfigParser.getfloat(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000994
995 A convenience method which coerces the *option* in the specified *section* to
996 a floating point number. See :meth:`get` for explanation of *raw*, *vars*
Łukasz Langa26d513c2010-11-10 18:57:39 +0000997 and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000998
999
Łukasz Langa26d513c2010-11-10 18:57:39 +00001000.. method:: ConfigParser.getboolean(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001001
1002 A convenience method which coerces the *option* in the specified *section*
1003 to a Boolean value. Note that the accepted values for the option are
1004 ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
1005 return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
1006 cause it to return ``False``. These string values are checked in
1007 a case-insensitive manner. Any other value will cause it to raise
1008 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
Łukasz Langa26d513c2010-11-10 18:57:39 +00001009 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001010
1011
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001012.. method:: ConfigParser.items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001013
Georg Brandl96a60ae2010-07-28 13:13:46 +00001014 Return a list of ``(name, value)`` pairs for each option in the given
1015 *section*. Optional arguments have the same meaning as for the :meth:`get`
1016 method.
Georg Brandl116aa622007-08-15 14:28:22 +00001017
Georg Brandl116aa622007-08-15 14:28:22 +00001018
Łukasz Langa26d513c2010-11-10 18:57:39 +00001019.. data:: MAX_INTERPOLATION_DEPTH
1020
1021 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1022 parameter is false. This is relevant only for the :class:`ConfigParser` class.
1023
Georg Brandl116aa622007-08-15 14:28:22 +00001024.. _safeconfigparser-objects:
1025
1026SafeConfigParser Objects
1027------------------------
1028
Łukasz Langa26d513c2010-11-10 18:57:39 +00001029.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
1030
1031 Derived class of :class:`ConfigParser` that implements a sane variant of the
1032 magical interpolation feature. This implementation is more predictable as it
1033 validates the interpolation syntax used within a configuration file. This
1034 class also enables escaping the interpolation character (e.g. a key can have
1035 ``%`` as part of the value by specifying ``%%`` in the file).
1036
1037 Applications that don't require interpolation should use
1038 :class:`RawConfigParser`, otherwise :class:`SafeConfigParser` is the best
1039 option.
1040
1041 .. versionchanged:: 3.1
1042 The default *dict_type* is :class:`collections.OrderedDict`.
1043
1044 .. versionchanged:: 3.2
1045 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
1046 *empty_lines_in_values* were added.
1047
1048
Georg Brandl116aa622007-08-15 14:28:22 +00001049The :class:`SafeConfigParser` class implements the same extended interface as
1050:class:`ConfigParser`, with the following addition:
1051
Georg Brandl116aa622007-08-15 14:28:22 +00001052.. method:: SafeConfigParser.set(section, option, value)
1053
1054 If the given section exists, set the given option to the specified value;
Georg Brandlf6945182008-02-01 11:56:49 +00001055 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
1056 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001057
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001058
Łukasz Langa26d513c2010-11-10 18:57:39 +00001059Exceptions
1060----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001061
Łukasz Langa26d513c2010-11-10 18:57:39 +00001062.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001063
Łukasz Langa26d513c2010-11-10 18:57:39 +00001064 Base class for all other configparser exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001065
Georg Brandl48310cd2009-01-03 21:18:54 +00001066
Łukasz Langa26d513c2010-11-10 18:57:39 +00001067.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001068
Łukasz Langa26d513c2010-11-10 18:57:39 +00001069 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001070
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001071
Łukasz Langa26d513c2010-11-10 18:57:39 +00001072.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001073
Łukasz Langa26d513c2010-11-10 18:57:39 +00001074 Exception raised if :meth:`add_section` is called with the name of a section
1075 that is already present or in strict parsers when a section if found more
1076 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001077
Łukasz Langa26d513c2010-11-10 18:57:39 +00001078 .. versionadded:: 3.2
1079 Optional ``source`` and ``lineno`` attributes and arguments to
1080 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001081
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001082
Łukasz Langa26d513c2010-11-10 18:57:39 +00001083.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001084
Łukasz Langa26d513c2010-11-10 18:57:39 +00001085 Exception raised by strict parsers if a single option appears twice during
1086 reading from a single file, string or dictionary. This catches misspellings
1087 and case sensitivity-related errors, e.g. a dictionary may have two keys
1088 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001089
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001090
Łukasz Langa26d513c2010-11-10 18:57:39 +00001091.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001092
Łukasz Langa26d513c2010-11-10 18:57:39 +00001093 Exception raised when a specified option is not found in the specified
1094 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001095
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001096
Łukasz Langa26d513c2010-11-10 18:57:39 +00001097.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001098
Łukasz Langa26d513c2010-11-10 18:57:39 +00001099 Base class for exceptions raised when problems occur performing string
1100 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001101
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001102
Łukasz Langa26d513c2010-11-10 18:57:39 +00001103.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001104
Łukasz Langa26d513c2010-11-10 18:57:39 +00001105 Exception raised when string interpolation cannot be completed because the
1106 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
1107 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001108
Fred Drake03c44a32010-02-19 06:08:41 +00001109
Łukasz Langa26d513c2010-11-10 18:57:39 +00001110.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001111
Łukasz Langa26d513c2010-11-10 18:57:39 +00001112 Exception raised when an option referenced from a value does not exist. Subclass
1113 of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001114
Fred Drake03c44a32010-02-19 06:08:41 +00001115
Łukasz Langa26d513c2010-11-10 18:57:39 +00001116.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001117
Łukasz Langa26d513c2010-11-10 18:57:39 +00001118 Exception raised when the source text into which substitutions are made does not
1119 conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001120
Łukasz Langa26d513c2010-11-10 18:57:39 +00001121
1122.. exception:: MissingSectionHeaderError
1123
1124 Exception raised when attempting to parse a file which has no section headers.
1125
1126
1127.. exception:: ParsingError
1128
1129 Exception raised when errors occur attempting to parse a file.
1130
1131 .. versionchanged:: 3.2
1132 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1133 ``source`` for consistency.
1134
1135.. [customizable] Config parsers allow for very heavy customization. If you're
1136 interested in changing the behaviour outlined by the footnote
1137 reference, consult the `Customizing Parser Behaviour`_ section.