blob: 8977e8fe2d7d68c3f96ede8c63fe1231668a330a [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
Fred Drake5a7c11f2010-11-13 05:24:17 +000021:class:`SafeConfigParser`. They implement a basic configuration
22language which provides a structure similar to what's found in Microsoft
Georg Brandl96a60ae2010-07-28 13:13:46 +000023Windows 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
Georg Brandlbb27c122010-11-11 07:26:40 +000037
Łukasz Langa26d513c2010-11-10 18:57:39 +000038Quick Start
39-----------
40
Georg Brandlbb27c122010-11-11 07:26:40 +000041Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000042
Georg Brandlbb27c122010-11-11 07:26:40 +000043.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000044
Georg Brandlbb27c122010-11-11 07:26:40 +000045 [DEFAULT]
46 ServerAliveInterval = 45
47 Compression = yes
48 CompressionLevel = 9
49 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000050
Georg Brandlbb27c122010-11-11 07:26:40 +000051 [bitbucket.org]
52 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000053
Georg Brandlbb27c122010-11-11 07:26:40 +000054 [topsecret.server.com]
55 Port = 50022
56 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000057
Fred Drake5a7c11f2010-11-13 05:24:17 +000058The structure of INI files is described `in the following section
59<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000060consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000061:mod:`configparser` classes can read and write such files. Let's start by
Łukasz Langa26d513c2010-11-10 18:57:39 +000062creating the above configuration file programatically.
63
Łukasz Langa26d513c2010-11-10 18:57:39 +000064.. doctest::
65
Georg Brandlbb27c122010-11-11 07:26:40 +000066 >>> 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 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000081
Fred Drake5a7c11f2010-11-13 05:24:17 +000082As you can see, we can treat a config parser much like a dictionary.
83There are differences, `outlined later <#mapping-protocol-access>`_, but
84the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000085
Fred Drake5a7c11f2010-11-13 05:24:17 +000086Now that we have created and saved a configuration file, let's read it
87back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +000088
Łukasz Langa26d513c2010-11-10 18:57:39 +000089.. doctest::
90
Georg Brandlbb27c122010-11-11 07:26:40 +000091 >>> import configparser
92 >>> config = configparser.RawConfigParser()
93 >>> config.sections()
94 []
95 >>> config.read('example.ini')
96 ['example.ini']
97 >>> config.sections()
98 ['bitbucket.org', 'topsecret.server.com']
99 >>> 'bitbucket.org' in config
100 True
101 >>> 'bytebong.com' in config
102 False
103 >>> config['bitbucket.org']['User']
104 'hg'
105 >>> config['DEFAULT']['Compression']
106 'yes'
107 >>> topsecret = config['topsecret.server.com']
108 >>> topsecret['ForwardX11']
109 'no'
110 >>> topsecret['Port']
111 '50022'
112 >>> for key in config['bitbucket.org']: print(key)
113 ...
114 user
115 compressionlevel
116 serveraliveinterval
117 compression
118 forwardx11
119 >>> config['bitbucket.org']['ForwardX11']
120 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000121
Fred Drake5a7c11f2010-11-13 05:24:17 +0000122As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000123involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000124sections [1]_. Note also that keys in sections are
125case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000126
Łukasz Langa26d513c2010-11-10 18:57:39 +0000127
128Supported Datatypes
129-------------------
130
131Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000132storing them internally as strings. This means that if you need other
133datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000134
Łukasz Langa26d513c2010-11-10 18:57:39 +0000135.. doctest::
136
Georg Brandlbb27c122010-11-11 07:26:40 +0000137 >>> int(topsecret['Port'])
138 50022
139 >>> float(topsecret['CompressionLevel'])
140 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000141
Fred Drake5a7c11f2010-11-13 05:24:17 +0000142Extracting Boolean values is not that simple, though. Passing the value
143to ``bool()`` would do no good since ``bool('False')`` is still
144``True``. This is why config parsers also provide :meth:`getboolean`.
145This method is case-insensitive and recognizes Boolean values from
146``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [1]_.
147For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000148
Łukasz Langa26d513c2010-11-10 18:57:39 +0000149.. doctest::
150
Georg Brandlbb27c122010-11-11 07:26:40 +0000151 >>> topsecret.getboolean('ForwardX11')
152 False
153 >>> config['bitbucket.org'].getboolean('ForwardX11')
154 True
155 >>> config.getboolean('bitbucket.org', 'Compression')
156 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000157
158Apart from :meth:`getboolean`, config parsers also provide equivalent
Fred Drake5a7c11f2010-11-13 05:24:17 +0000159:meth:`getint` and :meth:`getfloat` methods, but these are far less
160useful since conversion using :func:`int` and :func:`float` is
161sufficient for these types.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000162
Georg Brandlbb27c122010-11-11 07:26:40 +0000163
Łukasz Langa26d513c2010-11-10 18:57:39 +0000164Fallback Values
165---------------
166
Fred Drake5a7c11f2010-11-13 05:24:17 +0000167As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000168provide fallback values:
169
Łukasz Langa26d513c2010-11-10 18:57:39 +0000170.. doctest::
171
Georg Brandlbb27c122010-11-11 07:26:40 +0000172 >>> topsecret.get('Port')
173 '50022'
174 >>> topsecret.get('CompressionLevel')
175 '9'
176 >>> topsecret.get('Cipher')
177 >>> topsecret.get('Cipher', '3des-cbc')
178 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000179
Fred Drake5a7c11f2010-11-13 05:24:17 +0000180Please note that default values have precedence over fallback values.
181For instance, in our example the ``'CompressionLevel'`` key was
182specified only in the ``'DEFAULT'`` section. If we try to get it from
183the section ``'topsecret.server.com'``, we will always get the default,
184even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000185
Łukasz Langa26d513c2010-11-10 18:57:39 +0000186.. doctest::
187
Georg Brandlbb27c122010-11-11 07:26:40 +0000188 >>> topsecret.get('CompressionLevel', '3')
189 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000190
191One more thing to be aware of is that the parser-level :meth:`get` method
192provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000193compatibility. When using this method, a fallback value can be provided via
194the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000195
Łukasz Langa26d513c2010-11-10 18:57:39 +0000196.. doctest::
197
Georg Brandlbb27c122010-11-11 07:26:40 +0000198 >>> config.get('bitbucket.org', 'monster',
199 ... fallback='No such things as monsters')
200 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000201
202The same ``fallback`` argument can be used with the :meth:`getint`,
203:meth:`getfloat` and :meth:`getboolean` methods, for example:
204
Łukasz Langa26d513c2010-11-10 18:57:39 +0000205.. doctest::
206
Georg Brandlbb27c122010-11-11 07:26:40 +0000207 >>> 'BatchMode' in topsecret
208 False
209 >>> topsecret.getboolean('BatchMode', fallback=True)
210 True
211 >>> config['DEFAULT']['BatchMode'] = 'no'
212 >>> topsecret.getboolean('BatchMode', fallback=True)
213 False
214
Łukasz Langa26d513c2010-11-10 18:57:39 +0000215
216Supported INI File Structure
217----------------------------
218
Georg Brandl96a60ae2010-07-28 13:13:46 +0000219A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000220followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000221default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000222[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000223Values can be omitted, in which case the key/value delimiter may also be left
224out. Values can also span multiple lines, as long as they are indented deeper
225than the first line of the value. Depending on the parser's mode, blank lines
226may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000227
Fred Drake5a7c11f2010-11-13 05:24:17 +0000228Configuration files may include comments, prefixed by specific
229characters (``#`` and ``;`` by default [1]_). Comments may appear on
230their own on an otherwise empty line, or may be entered on lines holding
231values or section names. In the latter case, they need to be preceded
232by a whitespace character to be recognized as a comment. For backwards
233compatibility, by default only ``;`` starts an inline comment, while
234``#`` does not [1]_.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000235
236On top of the core functionality, :class:`SafeConfigParser` supports
237interpolation. This means values can contain format strings which refer to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000238other values in the same section, or values in a special ``DEFAULT`` section
Georg Brandlbb27c122010-11-11 07:26:40 +0000239[1]_. Additional defaults can be provided on initialization.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000240
Georg Brandlbb27c122010-11-11 07:26:40 +0000241For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Georg Brandlbb27c122010-11-11 07:26:40 +0000243.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000244
Georg Brandl96a60ae2010-07-28 13:13:46 +0000245 [Paths]
246 home_dir: /Users
247 my_dir: %(home_dir)s/lumberjack
248 my_pictures: %(my_dir)s/Pictures
Georg Brandl116aa622007-08-15 14:28:22 +0000249
Georg Brandl96a60ae2010-07-28 13:13:46 +0000250 [Multiline Values]
251 chorus: I'm a lumberjack, and I'm okay
252 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000253
Georg Brandl96a60ae2010-07-28 13:13:46 +0000254 [No Values]
255 key_without_value
256 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandl96a60ae2010-07-28 13:13:46 +0000258 [You can use comments] ; after a useful line
259 ; in an empty line
260 after: a_value ; here's another comment
261 inside: a ;comment
262 multiline ;comment
263 value! ;comment
264
265 [Sections Can Be Indented]
266 can_values_be_as_well = True
267 does_that_mean_anything_special = False
268 purpose = formatting for readability
269 multiline_values = are
270 handled just fine as
271 long as they are indented
272 deeper than the first line
273 of a value
274 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000275
Georg Brandl96a60ae2010-07-28 13:13:46 +0000276In the example above, :class:`SafeConfigParser` would resolve ``%(home_dir)s``
277to the value of ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in
278effect would resolve to ``/Users/lumberjack``. All interpolations are done on
279demand so keys used in the chain of references do not have to be specified in
280any specific order in the configuration file.
281
282:class:`RawConfigParser` would simply return ``%(my_dir)s/Pictures`` as the
283value of ``my_pictures`` and ``%(home_dir)s/lumberjack`` as the value of
284``my_dir``. Other features presented in the example are handled in the same
285manner by both parsers.
286
Georg Brandlbb27c122010-11-11 07:26:40 +0000287
Łukasz Langa26d513c2010-11-10 18:57:39 +0000288Mapping Protocol Access
289-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000290
Łukasz Langa26d513c2010-11-10 18:57:39 +0000291.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000292
Łukasz Langa26d513c2010-11-10 18:57:39 +0000293Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000294custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000295the mapping interface implementation is using the
296``parser['section']['option']`` notation.
297
298``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000299the parser. This means that the values are not copied but they are taken from
300the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000301are changed on a section proxy, they are actually mutated in the original
302parser.
303
304:mod:`configparser` objects behave as close to actual dictionaries as possible.
305The mapping interface is complete and adheres to the ``MutableMapping`` ABC.
306However, there are a few differences that should be taken into account:
307
Georg Brandlbb27c122010-11-11 07:26:40 +0000308* By default, all keys in sections are accessible in a case-insensitive manner
309 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
310 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000311 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000312
Georg Brandlbb27c122010-11-11 07:26:40 +0000313 "a" in parser["section"]
314 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000315
Georg Brandlbb27c122010-11-11 07:26:40 +0000316* All sections include ``DEFAULTSECT`` values as well which means that
317 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000318 because default values cannot be deleted from the section (because technically
Georg Brandlbb27c122010-11-11 07:26:40 +0000319 they are not there). If they are overriden in the section, deleting causes
320 the default value to be visible again. Trying to delete a default value
321 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000322
Georg Brandlbb27c122010-11-11 07:26:40 +0000323* Trying to delete the ``DEFAULTSECT`` throws ``ValueError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000324
Georg Brandlbb27c122010-11-11 07:26:40 +0000325* There are two parser-level methods in the legacy API that hide the dictionary
326 interface and are incompatible:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000327
Georg Brandlbb27c122010-11-11 07:26:40 +0000328 * ``parser.get(section, option, **kwargs)`` - the second argument is **not** a
329 fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000330
Fred Drake5a7c11f2010-11-13 05:24:17 +0000331 * ``parser.items(section)`` - this returns a list of *option*, *value* pairs
Georg Brandlbb27c122010-11-11 07:26:40 +0000332 for a specified ``section``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000333
334The mapping protocol is implemented on top of the existing legacy API so that
335subclassing the original interface makes the mappings work as expected as well.
Fred Drake5a7c11f2010-11-13 05:24:17 +0000336One difference is the explicit lack of support for the ``'__name__'`` special
337key. This is because the existing behavior of ``'__name__'`` is very
338inconsistent and supporting it would only lead to problems. Details `here
Łukasz Langa26d513c2010-11-10 18:57:39 +0000339<http://mail.python.org/pipermail/python-dev/2010-July/102556.html>`_.
340
Georg Brandlbb27c122010-11-11 07:26:40 +0000341
Łukasz Langa26d513c2010-11-10 18:57:39 +0000342Customizing Parser Behaviour
343----------------------------
344
345There are nearly as many INI format variants as there are applications using it.
346:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000347set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000348historical background and it's very likely that you will want to customize some
349of the features.
350
Fred Drake5a7c11f2010-11-13 05:24:17 +0000351The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000352the :meth:`__init__` options:
353
354* *defaults*, default value: ``None``
355
356 This option accepts a dictionary of key-value pairs which will be initially
Georg Brandlbb27c122010-11-11 07:26:40 +0000357 put in the ``DEFAULTSECT``. This makes for an elegant way to support concise
Łukasz Langa26d513c2010-11-10 18:57:39 +0000358 configuration files that don't specify values which are the same as the
359 documented default.
360
Fred Drake5a7c11f2010-11-13 05:24:17 +0000361 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000362 :meth:`read_dict` before you read the actual file.
363
364* *dict_type*, default value: :class:`collections.OrderedDict`
365
366 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000367 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000368 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000369 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000370
371 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000372 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000373 reasons.
374
375 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000376 operation. When you use a regular dictionary in those operations, the order
377 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000378
Łukasz Langa26d513c2010-11-10 18:57:39 +0000379 .. doctest::
380
Georg Brandlbb27c122010-11-11 07:26:40 +0000381 >>> parser = configparser.RawConfigParser()
382 >>> parser.read_dict({'section1': {'key1': 'value1',
383 ... 'key2': 'value2',
384 ... 'key3': 'value3'},
385 ... 'section2': {'keyA': 'valueA',
386 ... 'keyB': 'valueB',
387 ... 'keyC': 'valueC'},
388 ... 'section3': {'foo': 'x',
389 ... 'bar': 'y',
390 ... 'baz': 'z'}
391 ... })
392 >>> parser.sections()
393 ['section3', 'section2', 'section1']
394 >>> [option for option in parser['section3']]
395 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000396
397 In these operations you need to use an ordered dictionary as well:
398
Łukasz Langa26d513c2010-11-10 18:57:39 +0000399 .. doctest::
400
Georg Brandlbb27c122010-11-11 07:26:40 +0000401 >>> from collections import OrderedDict
402 >>> parser = configparser.RawConfigParser()
403 >>> parser.read_dict(
404 ... OrderedDict((
405 ... ('s1',
406 ... OrderedDict((
407 ... ('1', '2'),
408 ... ('3', '4'),
409 ... ('5', '6'),
410 ... ))
411 ... ),
412 ... ('s2',
413 ... OrderedDict((
414 ... ('a', 'b'),
415 ... ('c', 'd'),
416 ... ('e', 'f'),
417 ... ))
418 ... ),
419 ... ))
420 ... )
421 >>> parser.sections()
422 ['s1', 's2']
423 >>> [option for option in parser['s1']]
424 ['1', '3', '5']
425 >>> [option for option in parser['s2'].values()]
426 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000427
428* *allow_no_value*, default value: ``False``
429
430 Some configuration files are known to include settings without values, but
431 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000432 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000433 indicate that such values should be accepted:
434
Łukasz Langa26d513c2010-11-10 18:57:39 +0000435 .. doctest::
436
Georg Brandlbb27c122010-11-11 07:26:40 +0000437 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000438
Georg Brandlbb27c122010-11-11 07:26:40 +0000439 >>> sample_config = """
440 ... [mysqld]
441 ... user = mysql
442 ... pid-file = /var/run/mysqld/mysqld.pid
443 ... skip-external-locking
444 ... old_passwords = 1
445 ... skip-bdb
446 ... skip-innodb # we don't need ACID today
447 ... """
448 >>> config = configparser.RawConfigParser(allow_no_value=True)
449 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000450
Georg Brandlbb27c122010-11-11 07:26:40 +0000451 >>> # Settings with values are treated as before:
452 >>> config["mysqld"]["user"]
453 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000454
Georg Brandlbb27c122010-11-11 07:26:40 +0000455 >>> # Settings without values provide None:
456 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000457
Georg Brandlbb27c122010-11-11 07:26:40 +0000458 >>> # Settings which aren't specified still raise an error:
459 >>> config["mysqld"]["does-not-exist"]
460 Traceback (most recent call last):
461 ...
462 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000463
464* *delimiters*, default value: ``('=', ':')``
465
466 Delimiters are substrings that delimit keys from values within a section. The
467 first occurence of a delimiting substring on a line is considered a delimiter.
Fred Drake5a7c11f2010-11-13 05:24:17 +0000468 This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000469
470 See also the *space_around_delimiters* argument to
471 :meth:`RawConfigParser.write`.
472
473* *comment_prefixes*, default value: ``_COMPATIBLE`` (``'#'`` valid on empty
474 lines, ``';'`` valid also on non-empty lines)
475
Fred Drake5a7c11f2010-11-13 05:24:17 +0000476 Comment prefixes are strings that indicate the start of a valid comment
Georg Brandlbb27c122010-11-11 07:26:40 +0000477 within a config file. The peculiar default value allows for comments starting
Łukasz Langa26d513c2010-11-10 18:57:39 +0000478 with ``'#'`` or ``';'`` but only the latter can be used in a non-empty line.
Georg Brandlbb27c122010-11-11 07:26:40 +0000479 This is obviously dictated by backwards compatibiliy. A more predictable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000480 approach would be to specify prefixes as ``('#', ';')`` which will allow for
481 both prefixes to be used in non-empty lines.
482
483 Please note that config parsers don't support escaping of comment prefixes so
484 leaving characters out of *comment_prefixes* is a way of ensuring they can be
485 used as parts of keys or values.
486
487* *strict*, default value: ``False``
488
489 If set to ``True``, the parser will not allow for any section or option
490 duplicates while reading from a single source (using :meth:`read_file`,
Georg Brandlbb27c122010-11-11 07:26:40 +0000491 :meth:`read_string` or :meth:`read_dict`). The default is ``False`` only
492 because of backwards compatibility reasons. It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000493 parsers in new applications.
494
495* *empty_lines_in_values*, default value: ``True``
496
Fred Drake5a7c11f2010-11-13 05:24:17 +0000497 In config parsers, values can span multiple lines as long as they are
498 indented more than the key that holds them. By default parsers also let
499 empty lines to be parts of values. At the same time, keys can be arbitrarily
500 indented themselves to improve readability. In consequence, when
501 configuration files get big and complex, it is easy for the user to lose
502 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000503
Georg Brandlbb27c122010-11-11 07:26:40 +0000504 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000505
Georg Brandlbb27c122010-11-11 07:26:40 +0000506 [Section]
507 key = multiline
508 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000509
Georg Brandlbb27c122010-11-11 07:26:40 +0000510 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000511
512
Georg Brandlbb27c122010-11-11 07:26:40 +0000513 This can be especially problematic for the user to see if she's using a
514 proportional font to edit the file. That is why when your application does
515 not need values with empty lines, you should consider disallowing them. This
516 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000517 produce two keys, ``key`` and ``this``.
518
Łukasz Langa26d513c2010-11-10 18:57:39 +0000519
Fred Drake5a7c11f2010-11-13 05:24:17 +0000520More advanced customization may be achieved by overriding default values of
521these parser attributes. The defaults are defined on the classes, so they
522may be overriden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000523
Fred Drake5a7c11f2010-11-13 05:24:17 +0000524.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000525
526 By default when using :meth:`getboolean`, config parsers consider the
527 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000528 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
529 can override this by specifying a custom dictionary of strings and their
Fred Drake5a7c11f2010-11-13 05:24:17 +0000530 Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000531
Łukasz Langa26d513c2010-11-10 18:57:39 +0000532 .. doctest::
533
Georg Brandlbb27c122010-11-11 07:26:40 +0000534 >>> custom = configparser.RawConfigParser()
535 >>> custom['section1'] = {'funky': 'nope'}
536 >>> custom['section1'].getboolean('funky')
537 Traceback (most recent call last):
538 ...
539 ValueError: Not a boolean: nope
540 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
541 >>> custom['section1'].getboolean('funky')
542 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000543
Fred Drake5a7c11f2010-11-13 05:24:17 +0000544 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000545 ``enabled``/``disabled``.
546
Fred Drake5a7c11f2010-11-13 05:24:17 +0000547.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000548
Fred Drake5a7c11f2010-11-13 05:24:17 +0000549 This method transforms option names on every read, get, or set
550 operation. The default converts the name to lowercase. This also
551 means that when a configuration file gets written, all keys will be
552 lowercase. Override this method if that's unsuitable.
553 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000554
Łukasz Langa26d513c2010-11-10 18:57:39 +0000555 .. doctest::
556
Georg Brandlbb27c122010-11-11 07:26:40 +0000557 >>> config = """
558 ... [Section1]
559 ... Key = Value
560 ...
561 ... [Section2]
562 ... AnotherKey = Value
563 ... """
564 >>> typical = configparser.RawConfigParser()
565 >>> typical.read_string(config)
566 >>> list(typical['Section1'].keys())
567 ['key']
568 >>> list(typical['Section2'].keys())
569 ['anotherkey']
570 >>> custom = configparser.RawConfigParser()
571 >>> custom.optionxform = lambda option: option
572 >>> custom.read_string(config)
573 >>> list(custom['Section1'].keys())
574 ['Key']
575 >>> list(custom['Section2'].keys())
576 ['AnotherKey']
577
Łukasz Langa26d513c2010-11-10 18:57:39 +0000578
579Legacy API Examples
580-------------------
581
Georg Brandlbb27c122010-11-11 07:26:40 +0000582Mainly because of backwards compatibility concerns, :mod:`configparser` provides
583also a legacy API with explicit ``get``/``set`` methods. While there are valid
584use cases for the methods outlined below, mapping protocol access is preferred
585for new projects. The legacy API is at times more advanced, low-level and
586downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000587
588An example of writing to a configuration file::
589
590 import configparser
591
592 config = configparser.RawConfigParser()
593
594 # Please note that using RawConfigParser's and the raw mode of
595 # ConfigParser's respective set functions, you can assign non-string values
596 # to keys internally, but will receive an error when attempting to write to
597 # a file or when you get it in non-raw mode. Setting values using the
598 # mapping protocol or SafeConfigParser's set() does not allow such
599 # assignments to take place.
600 config.add_section('Section1')
601 config.set('Section1', 'int', '15')
602 config.set('Section1', 'bool', 'true')
603 config.set('Section1', 'float', '3.1415')
604 config.set('Section1', 'baz', 'fun')
605 config.set('Section1', 'bar', 'Python')
606 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
607
608 # Writing our configuration file to 'example.cfg'
609 with open('example.cfg', 'w') as configfile:
610 config.write(configfile)
611
612An example of reading the configuration file again::
613
614 import configparser
615
616 config = configparser.RawConfigParser()
617 config.read('example.cfg')
618
619 # getfloat() raises an exception if the value is not a float
620 # getint() and getboolean() also do this for their respective types
621 float = config.getfloat('Section1', 'float')
622 int = config.getint('Section1', 'int')
623 print(float + int)
624
625 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
626 # This is because we are using a RawConfigParser().
627 if config.getboolean('Section1', 'bool'):
628 print(config.get('Section1', 'foo'))
629
Fred Drake5a7c11f2010-11-13 05:24:17 +0000630To get interpolation, use :class:`SafeConfigParser` or, if
Łukasz Langa26d513c2010-11-10 18:57:39 +0000631you absolutely have to, a :class:`ConfigParser`::
632
633 import configparser
634
635 cfg = configparser.SafeConfigParser()
636 cfg.read('example.cfg')
637
638 # Set the optional `raw` argument of get() to True if you wish to disable
639 # interpolation in a single get operation.
640 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
641 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
642
643 # The optional `vars` argument is a dict with members that will take
644 # precedence in interpolation.
645 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
646 'baz': 'evil'}))
647
648 # The optional `fallback` argument can be used to provide a fallback value
649 print(cfg.get('Section1', 'foo'))
650 # -> "Python is fun!"
651
652 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
653 # -> "Python is fun!"
654
655 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
656 # -> "No such things as monsters."
657
658 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
659 # but we can also use:
660
661 print(cfg.get('Section1', 'monster', fallback=None))
662 # -> None
663
Fred Drake5a7c11f2010-11-13 05:24:17 +0000664Default values are available in all three types of ConfigParsers. They are
665used in interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000666
667 import configparser
668
669 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
670 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
671 config.read('example.cfg')
672
673 print(config.get('Section1', 'foo')) # -> "Python is fun!"
674 config.remove_option('Section1', 'bar')
675 config.remove_option('Section1', 'baz')
676 print(config.get('Section1', 'foo')) # -> "Life is hard!"
677
Georg Brandlbb27c122010-11-11 07:26:40 +0000678
Łukasz Langa26d513c2010-11-10 18:57:39 +0000679.. _rawconfigparser-objects:
680
681RawConfigParser Objects
682-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000683
Fred Drakea4923622010-08-09 12:52:45 +0000684.. 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 +0000685
Fred Drake5a7c11f2010-11-13 05:24:17 +0000686 The basic configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000687 into the dictionary of intrinsic defaults. When *dict_type* is given, it
688 will be used to create the dictionary objects for the list of sections, for
689 the options within a section, and for the default values.
690
Fred Drake5a7c11f2010-11-13 05:24:17 +0000691 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000692 divide keys from values. When *comment_prefixes* is given, it will be used
693 as the set of substrings that prefix comments in a line, both for the whole
694 line and inline comments. For backwards compatibility, the default value for
695 *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can
696 start whole line comments while only ``;`` can start inline comments.
697
Fred Drakea4923622010-08-09 12:52:45 +0000698 When *strict* is ``True`` (default: ``False``), the parser won't allow for
699 any section or option duplicates while reading from a single source (file,
700 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000701 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000702 (default: ``True``), each empty line marks the end of an option. Otherwise,
703 internal empty lines of a multiline option are kept as part of the value.
704 When *allow_no_value* is ``True`` (default: ``False``), options without
705 values are accepted; the value presented for these is ``None``.
Fred Drake03c44a32010-02-19 06:08:41 +0000706
Georg Brandl96a60ae2010-07-28 13:13:46 +0000707 This class does not support the magical interpolation behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000708
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000709 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000710 The default *dict_type* is :class:`collections.OrderedDict`.
711
Fred Drake03c44a32010-02-19 06:08:41 +0000712 .. versionchanged:: 3.2
Fred Drakea4923622010-08-09 12:52:45 +0000713 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
714 *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000715
Fred Drake03c44a32010-02-19 06:08:41 +0000716
Georg Brandlbb27c122010-11-11 07:26:40 +0000717 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000718
Georg Brandlbb27c122010-11-11 07:26:40 +0000719 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000720
721
Georg Brandlbb27c122010-11-11 07:26:40 +0000722 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000723
Georg Brandlbb27c122010-11-11 07:26:40 +0000724 Return a list of the sections available; ``DEFAULT`` is not included in
725 the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000726
727
Georg Brandlbb27c122010-11-11 07:26:40 +0000728 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Georg Brandlbb27c122010-11-11 07:26:40 +0000730 Add a section named *section* to the instance. If a section by the given
731 name already exists, :exc:`DuplicateSectionError` is raised. If the name
732 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
733 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000734
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Georg Brandlbb27c122010-11-11 07:26:40 +0000736 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Georg Brandlbb27c122010-11-11 07:26:40 +0000738 Indicates whether the named section is present in the configuration. The
739 ``DEFAULT`` section is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000740
Georg Brandl116aa622007-08-15 14:28:22 +0000741
Georg Brandlbb27c122010-11-11 07:26:40 +0000742 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Georg Brandlbb27c122010-11-11 07:26:40 +0000744 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000745
Georg Brandl116aa622007-08-15 14:28:22 +0000746
Georg Brandlbb27c122010-11-11 07:26:40 +0000747 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000748
Georg Brandlbb27c122010-11-11 07:26:40 +0000749 If the given section exists, and contains the given option, return
750 :const:`True`; otherwise return :const:`False`.
Georg Brandl116aa622007-08-15 14:28:22 +0000751
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Georg Brandlbb27c122010-11-11 07:26:40 +0000753 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000754
Georg Brandlbb27c122010-11-11 07:26:40 +0000755 Attempt to read and parse a list of filenames, returning a list of
756 filenames which were successfully parsed. If *filenames* is a string, it
757 is treated as a single filename. If a file named in *filenames* cannot be
758 opened, that file will be ignored. This is designed so that you can
759 specify a list of potential configuration file locations (for example, the
760 current directory, the user's home directory, and some system-wide
761 directory), and all existing configuration files in the list will be read.
762 If none of the named files exist, the :class:`ConfigParser` instance will
763 contain an empty dataset. An application which requires initial values to
764 be loaded from a file should load the required file or files using
765 :meth:`read_file` before calling :meth:`read` for any optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000766
Georg Brandlbb27c122010-11-11 07:26:40 +0000767 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000768
Georg Brandlbb27c122010-11-11 07:26:40 +0000769 config = configparser.ConfigParser()
770 config.read_file(open('defaults.cfg'))
771 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
772 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +0000773
Georg Brandlbb27c122010-11-11 07:26:40 +0000774 .. versionadded:: 3.2
775 The *encoding* parameter. Previously, all files were read using the
776 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000777
Georg Brandl116aa622007-08-15 14:28:22 +0000778
Georg Brandlbb27c122010-11-11 07:26:40 +0000779 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +0000780
Fred Drake5a7c11f2010-11-13 05:24:17 +0000781 Read and parse configuration data from the file or file-like object in
782 *f* (only the :meth:`readline` method is used). The file-like object
783 must operate in text mode. Specifically, it must return strings from
784 :meth:`readline`.
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Georg Brandlbb27c122010-11-11 07:26:40 +0000786 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +0000787 not given and *f* has a :attr:`name` attribute, that is used for
788 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +0000789
Georg Brandlbb27c122010-11-11 07:26:40 +0000790 .. versionadded:: 3.2
Fred Drake5a7c11f2010-11-13 05:24:17 +0000791 Replaces :meth:`readfp`.
Fred Drakea4923622010-08-09 12:52:45 +0000792
Fred Drakea4923622010-08-09 12:52:45 +0000793
Georg Brandlbb27c122010-11-11 07:26:40 +0000794 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +0000795
Fred Drake5a7c11f2010-11-13 05:24:17 +0000796 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +0000797
Fred Drake5a7c11f2010-11-13 05:24:17 +0000798 Optional argument *source* specifies a context-specific name of the
799 string passed. If not given, ``'<string>'`` is used. This should
800 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +0000801
Georg Brandlbb27c122010-11-11 07:26:40 +0000802 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000803
Fred Drakea4923622010-08-09 12:52:45 +0000804
Georg Brandlbb27c122010-11-11 07:26:40 +0000805 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +0000806
Georg Brandlbb27c122010-11-11 07:26:40 +0000807 Load configuration from a dictionary. Keys are section names, values are
808 dictionaries with keys and values that should be present in the section.
809 If the used dictionary type preserves order, sections and their keys will
810 be added in order. Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +0000811
Georg Brandlbb27c122010-11-11 07:26:40 +0000812 Optional argument *source* specifies a context-specific name of the
813 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000814
Georg Brandlbb27c122010-11-11 07:26:40 +0000815 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000816
Georg Brandlbb27c122010-11-11 07:26:40 +0000817 .. method:: get(section, option, [vars, fallback])
818
819 Get an *option* value for the named *section*. If *vars* is provided, it
820 must be a dictionary. The *option* is looked up in *vars* (if provided),
821 *section*, and in *DEFAULTSECT* in that order. If the key is not found
822 and *fallback* is provided, it is used as a fallback value. ``None`` can
823 be provided as a *fallback* value.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000824
Georg Brandlbb27c122010-11-11 07:26:40 +0000825 .. versionchanged:: 3.2
826 Arguments *vars* and *fallback* are keyword only to protect users from
827 trying to use the third argument as the *fallback* fallback (especially
828 when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830
Georg Brandlbb27c122010-11-11 07:26:40 +0000831 .. method:: getint(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000832
Georg Brandlbb27c122010-11-11 07:26:40 +0000833 A convenience method which coerces the *option* in the specified *section*
834 to an integer. See :meth:`get` for explanation of *vars* and *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000835
836
Georg Brandlbb27c122010-11-11 07:26:40 +0000837 .. method:: getfloat(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000838
Georg Brandlbb27c122010-11-11 07:26:40 +0000839 A convenience method which coerces the *option* in the specified *section*
840 to a floating point number. See :meth:`get` for explanation of *vars* and
841 *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000842
843
Georg Brandlbb27c122010-11-11 07:26:40 +0000844 .. method:: getboolean(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000845
Georg Brandlbb27c122010-11-11 07:26:40 +0000846 A convenience method which coerces the *option* in the specified *section*
847 to a Boolean value. Note that the accepted values for the option are
848 ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
849 return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
850 cause it to return ``False``. These string values are checked in a
851 case-insensitive manner. Any other value will cause it to raise
852 :exc:`ValueError`. See :meth:`get` for explanation of *vars* and
853 *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000854
855
Georg Brandlbb27c122010-11-11 07:26:40 +0000856 .. method:: items(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000857
Fred Drake5a7c11f2010-11-13 05:24:17 +0000858 Return a list of *name*, *value* pairs for each option in the given
Georg Brandlbb27c122010-11-11 07:26:40 +0000859 *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000860
861
Georg Brandlbb27c122010-11-11 07:26:40 +0000862 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000863
Georg Brandlbb27c122010-11-11 07:26:40 +0000864 If the given section exists, set the given option to the specified value;
865 otherwise raise :exc:`NoSectionError`. While it is possible to use
866 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
867 set to true) for *internal* storage of non-string values, full
868 functionality (including interpolation and output to files) can only be
869 achieved using string values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000870
Georg Brandlbb27c122010-11-11 07:26:40 +0000871 .. note::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000872
Georg Brandlbb27c122010-11-11 07:26:40 +0000873 This method lets users assign non-string values to keys internally.
874 This behaviour is unsupported and will cause errors when attempting to
875 write to a file or get it in non-raw mode. **Use the mapping protocol
876 API** which does not allow such assignments to take place.
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Georg Brandl116aa622007-08-15 14:28:22 +0000878
Georg Brandlbb27c122010-11-11 07:26:40 +0000879 .. method:: write(fileobject, space_around_delimiters=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000880
Georg Brandlbb27c122010-11-11 07:26:40 +0000881 Write a representation of the configuration to the specified :term:`file
882 object`, which must be opened in text mode (accepting strings). This
883 representation can be parsed by a future :meth:`read` call. If
Fred Drake5a7c11f2010-11-13 05:24:17 +0000884 *space_around_delimiters* is true, delimiters between
Georg Brandlbb27c122010-11-11 07:26:40 +0000885 keys and values are surrounded by spaces.
Georg Brandl116aa622007-08-15 14:28:22 +0000886
Georg Brandl116aa622007-08-15 14:28:22 +0000887
Georg Brandlbb27c122010-11-11 07:26:40 +0000888 .. method:: remove_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000889
Georg Brandlbb27c122010-11-11 07:26:40 +0000890 Remove the specified *option* from the specified *section*. If the
891 section does not exist, raise :exc:`NoSectionError`. If the option
892 existed to be removed, return :const:`True`; otherwise return
893 :const:`False`.
Georg Brandl116aa622007-08-15 14:28:22 +0000894
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Georg Brandlbb27c122010-11-11 07:26:40 +0000896 .. method:: remove_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000897
Georg Brandlbb27c122010-11-11 07:26:40 +0000898 Remove the specified *section* from the configuration. If the section in
899 fact existed, return ``True``. Otherwise return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000900
901
Georg Brandlbb27c122010-11-11 07:26:40 +0000902 .. method:: optionxform(option)
Georg Brandl116aa622007-08-15 14:28:22 +0000903
Georg Brandlbb27c122010-11-11 07:26:40 +0000904 Transforms the option name *option* as found in an input file or as passed
905 in by client code to the form that should be used in the internal
906 structures. The default implementation returns a lower-case version of
907 *option*; subclasses may override this or client code can set an attribute
908 of this name on instances to affect this behavior.
Georg Brandl495f7b52009-10-27 15:28:25 +0000909
Fred Drake5a7c11f2010-11-13 05:24:17 +0000910 You don't need to subclass the parser to use this method, you can also
911 set it on an instance, to a function that takes a string argument and
912 returns a string. Setting it to ``str``, for example, would make option
913 names case sensitive::
Georg Brandl495f7b52009-10-27 15:28:25 +0000914
Georg Brandlbb27c122010-11-11 07:26:40 +0000915 cfgparser = ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000916 cfgparser.optionxform = str
Georg Brandl495f7b52009-10-27 15:28:25 +0000917
Georg Brandlbb27c122010-11-11 07:26:40 +0000918 Note that when reading configuration files, whitespace around the option
Fred Drake5a7c11f2010-11-13 05:24:17 +0000919 names is stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000920
Georg Brandl67b21b72010-08-17 15:07:14 +0000921
Georg Brandlbb27c122010-11-11 07:26:40 +0000922 .. method:: readfp(fp, filename=None)
Fred Drakea4923622010-08-09 12:52:45 +0000923
Georg Brandlbb27c122010-11-11 07:26:40 +0000924 .. deprecated:: 3.2
Fred Drake5a7c11f2010-11-13 05:24:17 +0000925 Use :meth:`read_file` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000926
Georg Brandl67b21b72010-08-17 15:07:14 +0000927
Georg Brandl116aa622007-08-15 14:28:22 +0000928.. _configparser-objects:
929
930ConfigParser Objects
931--------------------
932
Łukasz Langa26d513c2010-11-10 18:57:39 +0000933.. warning::
Georg Brandlbb27c122010-11-11 07:26:40 +0000934 Whenever you can, consider using :class:`SafeConfigParser` which adds
935 validation and escaping for the interpolation.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000936
Georg Brandl116aa622007-08-15 14:28:22 +0000937The :class:`ConfigParser` class extends some methods of the
Łukasz Langa26d513c2010-11-10 18:57:39 +0000938:class:`RawConfigParser` interface, adding some optional arguments.
939
940.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
941
942 Derived class of :class:`RawConfigParser` that implements the magical
943 interpolation feature and adds optional arguments to the :meth:`get` and
944 :meth:`items` methods.
945
946 :class:`SafeConfigParser` is generally recommended over this class if you
947 need interpolation.
948
949 The values in *defaults* must be appropriate for the ``%()s`` string
Fred Drake5a7c11f2010-11-13 05:24:17 +0000950 interpolation. Note that ``'__name__'`` is an intrinsic default; its value
951 is the section name, and will override any value provided in *defaults*.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000952
953 All option names used in interpolation will be passed through the
954 :meth:`optionxform` method just like any other option name reference. For
955 example, using the default implementation of :meth:`optionxform` (which
956 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
957 %(BAR)s`` are equivalent.
958
959 .. versionchanged:: 3.1
960 The default *dict_type* is :class:`collections.OrderedDict`.
961
962 .. versionchanged:: 3.2
963 *allow_no_value*, *delimiters*, *comment_prefixes*,
964 *strict* and *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000965
966
Georg Brandlbb27c122010-11-11 07:26:40 +0000967 .. method:: get(section, option, raw=False, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000968
Georg Brandlbb27c122010-11-11 07:26:40 +0000969 Get an *option* value for the named *section*. If *vars* is provided, it
970 must be a dictionary. The *option* is looked up in *vars* (if provided),
971 *section*, and in *DEFAULTSECT* in that order. If the key is not found
972 and *fallback* is provided, it is used as a fallback value. ``None`` can
973 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +0000974
Georg Brandlbb27c122010-11-11 07:26:40 +0000975 All the ``'%'`` interpolations are expanded in the return values, unless
976 the *raw* argument is true. Values for interpolation keys are looked up
977 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +0000978
Georg Brandlbb27c122010-11-11 07:26:40 +0000979 .. versionchanged:: 3.2
980 Arguments *raw*, *vars* and *fallback* are keyword only to protect
981 users from trying to use the third argument as the *fallback* fallback
982 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000983
Łukasz Langa26d513c2010-11-10 18:57:39 +0000984
Georg Brandlbb27c122010-11-11 07:26:40 +0000985 .. method:: getint(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000986
Georg Brandlbb27c122010-11-11 07:26:40 +0000987 A convenience method which coerces the *option* in the specified *section*
988 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
989 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000990
991
Georg Brandlbb27c122010-11-11 07:26:40 +0000992 .. method:: getfloat(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000993
Georg Brandlbb27c122010-11-11 07:26:40 +0000994 A convenience method which coerces the *option* in the specified *section*
995 to a floating point number. See :meth:`get` for explanation of *raw*,
996 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000997
998
Georg Brandlbb27c122010-11-11 07:26:40 +0000999 .. method:: getboolean(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001000
Georg Brandlbb27c122010-11-11 07:26:40 +00001001 A convenience method which coerces the *option* in the specified *section*
1002 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001003 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1004 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001005 cause it to return ``False``. These string values are checked in a
1006 case-insensitive manner. Any other value will cause it to raise
1007 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1008 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001009
1010
Georg Brandlbb27c122010-11-11 07:26:40 +00001011 .. method:: items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Fred Drake5a7c11f2010-11-13 05:24:17 +00001013 Return a list of *name*, *value* pairs for the options in the given
Georg Brandlbb27c122010-11-11 07:26:40 +00001014 *section*. Optional arguments have the same meaning as for the
1015 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001016
Georg Brandl116aa622007-08-15 14:28:22 +00001017
Łukasz Langa26d513c2010-11-10 18:57:39 +00001018.. data:: MAX_INTERPOLATION_DEPTH
1019
1020 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1021 parameter is false. This is relevant only for the :class:`ConfigParser` class.
1022
Georg Brandlbb27c122010-11-11 07:26:40 +00001023
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
Fred Drake5a7c11f2010-11-13 05:24:17 +00001031 Derived class of :class:`ConfigParser` that implements a variant of the
1032 magical interpolation feature. This implementation is more predictable as
1033 it validates the interpolation syntax used within a configuration file.
1034 This class also enables escaping the interpolation character (a key can have
Łukasz Langa26d513c2010-11-10 18:57:39 +00001035 ``%`` 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
Fred Drake5a7c11f2010-11-13 05:24:17 +00001049 The :class:`SafeConfigParser` class implements the same extended interface
1050 as :class:`ConfigParser`, with the following addition:
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Georg Brandlbb27c122010-11-11 07:26:40 +00001052 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001053
Georg Brandlbb27c122010-11-11 07:26:40 +00001054 If the given section exists, set the given option to the specified value;
Fred Drake5a7c11f2010-11-13 05:24:17 +00001055 otherwise raise :exc:`NoSectionError`. *value* must be a string; if not,
1056 :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
Fred Drake5a7c11f2010-11-13 05:24:17 +00001064 Base class for all other :mod:`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
Georg Brandlbb27c122010-11-11 07:26:40 +00001106 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001107 :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
Georg Brandlbb27c122010-11-11 07:26:40 +00001112 Exception raised when an option referenced from a value does not exist.
1113 Subclass 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
Georg Brandlbb27c122010-11-11 07:26:40 +00001118 Exception raised when the source text into which substitutions are made does
1119 not 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
Georg Brandlbb27c122010-11-11 07:26:40 +00001124 Exception raised when attempting to parse a file which has no section
1125 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001126
1127
1128.. exception:: ParsingError
1129
1130 Exception raised when errors occur attempting to parse a file.
1131
1132 .. versionchanged:: 3.2
1133 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1134 ``source`` for consistency.
1135
Georg Brandlbb27c122010-11-11 07:26:40 +00001136
1137.. rubric:: Footnotes
1138
1139.. [1] Config parsers allow for heavy customization. If you are interested in
1140 changing the behaviour outlined by the footnote reference, consult the
1141 `Customizing Parser Behaviour`_ section.