blob: df7a1de15c4c6c85be84cc1a8afa4b582d218dc1 [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
Éric Araujoff2a4ba2010-11-30 17:20:31 +0000323* Trying to delete the ``DEFAULTSECT`` raises ``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.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000336
Georg Brandlbb27c122010-11-11 07:26:40 +0000337
Łukasz Langa26d513c2010-11-10 18:57:39 +0000338Customizing Parser Behaviour
339----------------------------
340
341There are nearly as many INI format variants as there are applications using it.
342:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000343set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000344historical background and it's very likely that you will want to customize some
345of the features.
346
Fred Drake5a7c11f2010-11-13 05:24:17 +0000347The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000348the :meth:`__init__` options:
349
350* *defaults*, default value: ``None``
351
352 This option accepts a dictionary of key-value pairs which will be initially
Georg Brandlbb27c122010-11-11 07:26:40 +0000353 put in the ``DEFAULTSECT``. This makes for an elegant way to support concise
Łukasz Langa26d513c2010-11-10 18:57:39 +0000354 configuration files that don't specify values which are the same as the
355 documented default.
356
Fred Drake5a7c11f2010-11-13 05:24:17 +0000357 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000358 :meth:`read_dict` before you read the actual file.
359
360* *dict_type*, default value: :class:`collections.OrderedDict`
361
362 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000363 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000364 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000365 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000366
367 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000368 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000369 reasons.
370
371 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000372 operation. When you use a regular dictionary in those operations, the order
373 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000374
Łukasz Langa26d513c2010-11-10 18:57:39 +0000375 .. doctest::
376
Georg Brandlbb27c122010-11-11 07:26:40 +0000377 >>> parser = configparser.RawConfigParser()
378 >>> parser.read_dict({'section1': {'key1': 'value1',
379 ... 'key2': 'value2',
380 ... 'key3': 'value3'},
381 ... 'section2': {'keyA': 'valueA',
382 ... 'keyB': 'valueB',
383 ... 'keyC': 'valueC'},
384 ... 'section3': {'foo': 'x',
385 ... 'bar': 'y',
386 ... 'baz': 'z'}
387 ... })
388 >>> parser.sections()
389 ['section3', 'section2', 'section1']
390 >>> [option for option in parser['section3']]
391 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000392
393 In these operations you need to use an ordered dictionary as well:
394
Łukasz Langa26d513c2010-11-10 18:57:39 +0000395 .. doctest::
396
Georg Brandlbb27c122010-11-11 07:26:40 +0000397 >>> from collections import OrderedDict
398 >>> parser = configparser.RawConfigParser()
399 >>> parser.read_dict(
400 ... OrderedDict((
401 ... ('s1',
402 ... OrderedDict((
403 ... ('1', '2'),
404 ... ('3', '4'),
405 ... ('5', '6'),
406 ... ))
407 ... ),
408 ... ('s2',
409 ... OrderedDict((
410 ... ('a', 'b'),
411 ... ('c', 'd'),
412 ... ('e', 'f'),
413 ... ))
414 ... ),
415 ... ))
416 ... )
417 >>> parser.sections()
418 ['s1', 's2']
419 >>> [option for option in parser['s1']]
420 ['1', '3', '5']
421 >>> [option for option in parser['s2'].values()]
422 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000423
424* *allow_no_value*, default value: ``False``
425
426 Some configuration files are known to include settings without values, but
427 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000428 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000429 indicate that such values should be accepted:
430
Łukasz Langa26d513c2010-11-10 18:57:39 +0000431 .. doctest::
432
Georg Brandlbb27c122010-11-11 07:26:40 +0000433 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000434
Georg Brandlbb27c122010-11-11 07:26:40 +0000435 >>> sample_config = """
436 ... [mysqld]
437 ... user = mysql
438 ... pid-file = /var/run/mysqld/mysqld.pid
439 ... skip-external-locking
440 ... old_passwords = 1
441 ... skip-bdb
442 ... skip-innodb # we don't need ACID today
443 ... """
444 >>> config = configparser.RawConfigParser(allow_no_value=True)
445 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000446
Georg Brandlbb27c122010-11-11 07:26:40 +0000447 >>> # Settings with values are treated as before:
448 >>> config["mysqld"]["user"]
449 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000450
Georg Brandlbb27c122010-11-11 07:26:40 +0000451 >>> # Settings without values provide None:
452 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000453
Georg Brandlbb27c122010-11-11 07:26:40 +0000454 >>> # Settings which aren't specified still raise an error:
455 >>> config["mysqld"]["does-not-exist"]
456 Traceback (most recent call last):
457 ...
458 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000459
460* *delimiters*, default value: ``('=', ':')``
461
462 Delimiters are substrings that delimit keys from values within a section. The
463 first occurence of a delimiting substring on a line is considered a delimiter.
Fred Drake5a7c11f2010-11-13 05:24:17 +0000464 This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000465
466 See also the *space_around_delimiters* argument to
467 :meth:`RawConfigParser.write`.
468
469* *comment_prefixes*, default value: ``_COMPATIBLE`` (``'#'`` valid on empty
470 lines, ``';'`` valid also on non-empty lines)
471
Fred Drake5a7c11f2010-11-13 05:24:17 +0000472 Comment prefixes are strings that indicate the start of a valid comment
Georg Brandlbb27c122010-11-11 07:26:40 +0000473 within a config file. The peculiar default value allows for comments starting
Łukasz Langa26d513c2010-11-10 18:57:39 +0000474 with ``'#'`` or ``';'`` but only the latter can be used in a non-empty line.
Georg Brandlbb27c122010-11-11 07:26:40 +0000475 This is obviously dictated by backwards compatibiliy. A more predictable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000476 approach would be to specify prefixes as ``('#', ';')`` which will allow for
477 both prefixes to be used in non-empty lines.
478
479 Please note that config parsers don't support escaping of comment prefixes so
480 leaving characters out of *comment_prefixes* is a way of ensuring they can be
481 used as parts of keys or values.
482
483* *strict*, default value: ``False``
484
485 If set to ``True``, the parser will not allow for any section or option
486 duplicates while reading from a single source (using :meth:`read_file`,
Georg Brandlbb27c122010-11-11 07:26:40 +0000487 :meth:`read_string` or :meth:`read_dict`). The default is ``False`` only
488 because of backwards compatibility reasons. It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000489 parsers in new applications.
490
491* *empty_lines_in_values*, default value: ``True``
492
Fred Drake5a7c11f2010-11-13 05:24:17 +0000493 In config parsers, values can span multiple lines as long as they are
494 indented more than the key that holds them. By default parsers also let
495 empty lines to be parts of values. At the same time, keys can be arbitrarily
496 indented themselves to improve readability. In consequence, when
497 configuration files get big and complex, it is easy for the user to lose
498 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000499
Georg Brandlbb27c122010-11-11 07:26:40 +0000500 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000501
Georg Brandlbb27c122010-11-11 07:26:40 +0000502 [Section]
503 key = multiline
504 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000505
Georg Brandlbb27c122010-11-11 07:26:40 +0000506 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000507
508
Georg Brandlbb27c122010-11-11 07:26:40 +0000509 This can be especially problematic for the user to see if she's using a
510 proportional font to edit the file. That is why when your application does
511 not need values with empty lines, you should consider disallowing them. This
512 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000513 produce two keys, ``key`` and ``this``.
514
Łukasz Langa26d513c2010-11-10 18:57:39 +0000515
Fred Drake5a7c11f2010-11-13 05:24:17 +0000516More advanced customization may be achieved by overriding default values of
517these parser attributes. The defaults are defined on the classes, so they
518may be overriden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000519
Fred Drake5a7c11f2010-11-13 05:24:17 +0000520.. attribute:: BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000521
522 By default when using :meth:`getboolean`, config parsers consider the
523 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000524 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
525 can override this by specifying a custom dictionary of strings and their
Fred Drake5a7c11f2010-11-13 05:24:17 +0000526 Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000527
Łukasz Langa26d513c2010-11-10 18:57:39 +0000528 .. doctest::
529
Georg Brandlbb27c122010-11-11 07:26:40 +0000530 >>> custom = configparser.RawConfigParser()
531 >>> custom['section1'] = {'funky': 'nope'}
532 >>> custom['section1'].getboolean('funky')
533 Traceback (most recent call last):
534 ...
535 ValueError: Not a boolean: nope
536 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
537 >>> custom['section1'].getboolean('funky')
538 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000539
Fred Drake5a7c11f2010-11-13 05:24:17 +0000540 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000541 ``enabled``/``disabled``.
542
Fred Drake5a7c11f2010-11-13 05:24:17 +0000543.. method:: optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000544
Fred Drake5a7c11f2010-11-13 05:24:17 +0000545 This method transforms option names on every read, get, or set
546 operation. The default converts the name to lowercase. This also
547 means that when a configuration file gets written, all keys will be
548 lowercase. Override this method if that's unsuitable.
549 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000550
Łukasz Langa26d513c2010-11-10 18:57:39 +0000551 .. doctest::
552
Georg Brandlbb27c122010-11-11 07:26:40 +0000553 >>> config = """
554 ... [Section1]
555 ... Key = Value
556 ...
557 ... [Section2]
558 ... AnotherKey = Value
559 ... """
560 >>> typical = configparser.RawConfigParser()
561 >>> typical.read_string(config)
562 >>> list(typical['Section1'].keys())
563 ['key']
564 >>> list(typical['Section2'].keys())
565 ['anotherkey']
566 >>> custom = configparser.RawConfigParser()
567 >>> custom.optionxform = lambda option: option
568 >>> custom.read_string(config)
569 >>> list(custom['Section1'].keys())
570 ['Key']
571 >>> list(custom['Section2'].keys())
572 ['AnotherKey']
573
Łukasz Langa26d513c2010-11-10 18:57:39 +0000574
575Legacy API Examples
576-------------------
577
Georg Brandlbb27c122010-11-11 07:26:40 +0000578Mainly because of backwards compatibility concerns, :mod:`configparser` provides
579also a legacy API with explicit ``get``/``set`` methods. While there are valid
580use cases for the methods outlined below, mapping protocol access is preferred
581for new projects. The legacy API is at times more advanced, low-level and
582downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000583
584An example of writing to a configuration file::
585
586 import configparser
587
588 config = configparser.RawConfigParser()
589
590 # Please note that using RawConfigParser's and the raw mode of
591 # ConfigParser's respective set functions, you can assign non-string values
592 # to keys internally, but will receive an error when attempting to write to
593 # a file or when you get it in non-raw mode. Setting values using the
594 # mapping protocol or SafeConfigParser's set() does not allow such
595 # assignments to take place.
596 config.add_section('Section1')
597 config.set('Section1', 'int', '15')
598 config.set('Section1', 'bool', 'true')
599 config.set('Section1', 'float', '3.1415')
600 config.set('Section1', 'baz', 'fun')
601 config.set('Section1', 'bar', 'Python')
602 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
603
604 # Writing our configuration file to 'example.cfg'
605 with open('example.cfg', 'w') as configfile:
606 config.write(configfile)
607
608An example of reading the configuration file again::
609
610 import configparser
611
612 config = configparser.RawConfigParser()
613 config.read('example.cfg')
614
615 # getfloat() raises an exception if the value is not a float
616 # getint() and getboolean() also do this for their respective types
617 float = config.getfloat('Section1', 'float')
618 int = config.getint('Section1', 'int')
619 print(float + int)
620
621 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
622 # This is because we are using a RawConfigParser().
623 if config.getboolean('Section1', 'bool'):
624 print(config.get('Section1', 'foo'))
625
Fred Drake5a7c11f2010-11-13 05:24:17 +0000626To get interpolation, use :class:`SafeConfigParser` or, if
Łukasz Langa26d513c2010-11-10 18:57:39 +0000627you absolutely have to, a :class:`ConfigParser`::
628
629 import configparser
630
631 cfg = configparser.SafeConfigParser()
632 cfg.read('example.cfg')
633
634 # Set the optional `raw` argument of get() to True if you wish to disable
635 # interpolation in a single get operation.
636 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
637 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
638
639 # The optional `vars` argument is a dict with members that will take
640 # precedence in interpolation.
641 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
642 'baz': 'evil'}))
643
644 # The optional `fallback` argument can be used to provide a fallback value
645 print(cfg.get('Section1', 'foo'))
646 # -> "Python is fun!"
647
648 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
649 # -> "Python is fun!"
650
651 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
652 # -> "No such things as monsters."
653
654 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
655 # but we can also use:
656
657 print(cfg.get('Section1', 'monster', fallback=None))
658 # -> None
659
Fred Drake5a7c11f2010-11-13 05:24:17 +0000660Default values are available in all three types of ConfigParsers. They are
661used in interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000662
663 import configparser
664
665 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
666 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
667 config.read('example.cfg')
668
669 print(config.get('Section1', 'foo')) # -> "Python is fun!"
670 config.remove_option('Section1', 'bar')
671 config.remove_option('Section1', 'baz')
672 print(config.get('Section1', 'foo')) # -> "Life is hard!"
673
Georg Brandlbb27c122010-11-11 07:26:40 +0000674
Łukasz Langa26d513c2010-11-10 18:57:39 +0000675.. _rawconfigparser-objects:
676
677RawConfigParser Objects
678-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000679
Fred Drakea4923622010-08-09 12:52:45 +0000680.. 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 +0000681
Fred Drake5a7c11f2010-11-13 05:24:17 +0000682 The basic configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000683 into the dictionary of intrinsic defaults. When *dict_type* is given, it
684 will be used to create the dictionary objects for the list of sections, for
685 the options within a section, and for the default values.
686
Fred Drake5a7c11f2010-11-13 05:24:17 +0000687 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000688 divide keys from values. When *comment_prefixes* is given, it will be used
689 as the set of substrings that prefix comments in a line, both for the whole
690 line and inline comments. For backwards compatibility, the default value for
691 *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can
692 start whole line comments while only ``;`` can start inline comments.
693
Fred Drakea4923622010-08-09 12:52:45 +0000694 When *strict* is ``True`` (default: ``False``), the parser won't allow for
695 any section or option duplicates while reading from a single source (file,
696 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000697 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000698 (default: ``True``), each empty line marks the end of an option. Otherwise,
699 internal empty lines of a multiline option are kept as part of the value.
700 When *allow_no_value* is ``True`` (default: ``False``), options without
701 values are accepted; the value presented for these is ``None``.
Fred Drake03c44a32010-02-19 06:08:41 +0000702
Georg Brandl96a60ae2010-07-28 13:13:46 +0000703 This class does not support the magical interpolation behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000704
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000705 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000706 The default *dict_type* is :class:`collections.OrderedDict`.
707
Fred Drake03c44a32010-02-19 06:08:41 +0000708 .. versionchanged:: 3.2
Fred Drakea4923622010-08-09 12:52:45 +0000709 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
710 *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Fred Drake03c44a32010-02-19 06:08:41 +0000712
Georg Brandlbb27c122010-11-11 07:26:40 +0000713 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000714
Georg Brandlbb27c122010-11-11 07:26:40 +0000715 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000716
717
Georg Brandlbb27c122010-11-11 07:26:40 +0000718 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Georg Brandlbb27c122010-11-11 07:26:40 +0000720 Return a list of the sections available; ``DEFAULT`` is not included in
721 the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000722
723
Georg Brandlbb27c122010-11-11 07:26:40 +0000724 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000725
Georg Brandlbb27c122010-11-11 07:26:40 +0000726 Add a section named *section* to the instance. If a section by the given
727 name already exists, :exc:`DuplicateSectionError` is raised. If the name
728 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
729 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Georg Brandl116aa622007-08-15 14:28:22 +0000731
Georg Brandlbb27c122010-11-11 07:26:40 +0000732 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandlbb27c122010-11-11 07:26:40 +0000734 Indicates whether the named section is present in the configuration. The
735 ``DEFAULT`` section is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Georg Brandl116aa622007-08-15 14:28:22 +0000737
Georg Brandlbb27c122010-11-11 07:26:40 +0000738 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Georg Brandlbb27c122010-11-11 07:26:40 +0000740 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000741
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Georg Brandlbb27c122010-11-11 07:26:40 +0000743 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Georg Brandlbb27c122010-11-11 07:26:40 +0000745 If the given section exists, and contains the given option, return
746 :const:`True`; otherwise return :const:`False`.
Georg Brandl116aa622007-08-15 14:28:22 +0000747
Georg Brandl116aa622007-08-15 14:28:22 +0000748
Georg Brandlbb27c122010-11-11 07:26:40 +0000749 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000750
Georg Brandlbb27c122010-11-11 07:26:40 +0000751 Attempt to read and parse a list of filenames, returning a list of
752 filenames which were successfully parsed. If *filenames* is a string, it
753 is treated as a single filename. If a file named in *filenames* cannot be
754 opened, that file will be ignored. This is designed so that you can
755 specify a list of potential configuration file locations (for example, the
756 current directory, the user's home directory, and some system-wide
757 directory), and all existing configuration files in the list will be read.
758 If none of the named files exist, the :class:`ConfigParser` instance will
759 contain an empty dataset. An application which requires initial values to
760 be loaded from a file should load the required file or files using
761 :meth:`read_file` before calling :meth:`read` for any optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000762
Georg Brandlbb27c122010-11-11 07:26:40 +0000763 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000764
Georg Brandlbb27c122010-11-11 07:26:40 +0000765 config = configparser.ConfigParser()
766 config.read_file(open('defaults.cfg'))
767 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
768 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +0000769
Georg Brandlbb27c122010-11-11 07:26:40 +0000770 .. versionadded:: 3.2
771 The *encoding* parameter. Previously, all files were read using the
772 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000773
Georg Brandl116aa622007-08-15 14:28:22 +0000774
Georg Brandlbb27c122010-11-11 07:26:40 +0000775 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +0000776
Fred Drake5a7c11f2010-11-13 05:24:17 +0000777 Read and parse configuration data from the file or file-like object in
778 *f* (only the :meth:`readline` method is used). The file-like object
779 must operate in text mode. Specifically, it must return strings from
780 :meth:`readline`.
Georg Brandl116aa622007-08-15 14:28:22 +0000781
Georg Brandlbb27c122010-11-11 07:26:40 +0000782 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +0000783 not given and *f* has a :attr:`name` attribute, that is used for
784 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +0000785
Georg Brandlbb27c122010-11-11 07:26:40 +0000786 .. versionadded:: 3.2
Fred Drake5a7c11f2010-11-13 05:24:17 +0000787 Replaces :meth:`readfp`.
Fred Drakea4923622010-08-09 12:52:45 +0000788
Fred Drakea4923622010-08-09 12:52:45 +0000789
Georg Brandlbb27c122010-11-11 07:26:40 +0000790 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +0000791
Fred Drake5a7c11f2010-11-13 05:24:17 +0000792 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +0000793
Fred Drake5a7c11f2010-11-13 05:24:17 +0000794 Optional argument *source* specifies a context-specific name of the
795 string passed. If not given, ``'<string>'`` is used. This should
796 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +0000797
Georg Brandlbb27c122010-11-11 07:26:40 +0000798 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000799
Fred Drakea4923622010-08-09 12:52:45 +0000800
Georg Brandlbb27c122010-11-11 07:26:40 +0000801 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +0000802
Georg Brandlbb27c122010-11-11 07:26:40 +0000803 Load configuration from a dictionary. Keys are section names, values are
804 dictionaries with keys and values that should be present in the section.
805 If the used dictionary type preserves order, sections and their keys will
806 be added in order. Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +0000807
Georg Brandlbb27c122010-11-11 07:26:40 +0000808 Optional argument *source* specifies a context-specific name of the
809 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000810
Georg Brandlbb27c122010-11-11 07:26:40 +0000811 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000812
Georg Brandlbb27c122010-11-11 07:26:40 +0000813 .. method:: get(section, option, [vars, fallback])
814
815 Get an *option* value for the named *section*. If *vars* is provided, it
816 must be a dictionary. The *option* is looked up in *vars* (if provided),
817 *section*, and in *DEFAULTSECT* in that order. If the key is not found
818 and *fallback* is provided, it is used as a fallback value. ``None`` can
819 be provided as a *fallback* value.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000820
Georg Brandlbb27c122010-11-11 07:26:40 +0000821 .. versionchanged:: 3.2
822 Arguments *vars* and *fallback* are keyword only to protect users from
823 trying to use the third argument as the *fallback* fallback (especially
824 when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826
Georg Brandlbb27c122010-11-11 07:26:40 +0000827 .. method:: getint(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000828
Georg Brandlbb27c122010-11-11 07:26:40 +0000829 A convenience method which coerces the *option* in the specified *section*
830 to an integer. See :meth:`get` for explanation of *vars* and *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000831
832
Georg Brandlbb27c122010-11-11 07:26:40 +0000833 .. method:: getfloat(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000834
Georg Brandlbb27c122010-11-11 07:26:40 +0000835 A convenience method which coerces the *option* in the specified *section*
836 to a floating point number. See :meth:`get` for explanation of *vars* and
837 *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000838
839
Georg Brandlbb27c122010-11-11 07:26:40 +0000840 .. method:: getboolean(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000841
Georg Brandlbb27c122010-11-11 07:26:40 +0000842 A convenience method which coerces the *option* in the specified *section*
843 to a Boolean value. Note that the accepted values for the option are
844 ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
845 return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
846 cause it to return ``False``. These string values are checked in a
847 case-insensitive manner. Any other value will cause it to raise
848 :exc:`ValueError`. See :meth:`get` for explanation of *vars* and
849 *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851
Georg Brandlbb27c122010-11-11 07:26:40 +0000852 .. method:: items(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000853
Fred Drake5a7c11f2010-11-13 05:24:17 +0000854 Return a list of *name*, *value* pairs for each option in the given
Georg Brandlbb27c122010-11-11 07:26:40 +0000855 *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000856
857
Georg Brandlbb27c122010-11-11 07:26:40 +0000858 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000859
Georg Brandlbb27c122010-11-11 07:26:40 +0000860 If the given section exists, set the given option to the specified value;
861 otherwise raise :exc:`NoSectionError`. While it is possible to use
862 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
863 set to true) for *internal* storage of non-string values, full
864 functionality (including interpolation and output to files) can only be
865 achieved using string values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000866
Georg Brandlbb27c122010-11-11 07:26:40 +0000867 .. note::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000868
Georg Brandlbb27c122010-11-11 07:26:40 +0000869 This method lets users assign non-string values to keys internally.
870 This behaviour is unsupported and will cause errors when attempting to
871 write to a file or get it in non-raw mode. **Use the mapping protocol
872 API** which does not allow such assignments to take place.
Georg Brandl116aa622007-08-15 14:28:22 +0000873
Georg Brandl116aa622007-08-15 14:28:22 +0000874
Georg Brandlbb27c122010-11-11 07:26:40 +0000875 .. method:: write(fileobject, space_around_delimiters=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000876
Georg Brandlbb27c122010-11-11 07:26:40 +0000877 Write a representation of the configuration to the specified :term:`file
878 object`, which must be opened in text mode (accepting strings). This
879 representation can be parsed by a future :meth:`read` call. If
Fred Drake5a7c11f2010-11-13 05:24:17 +0000880 *space_around_delimiters* is true, delimiters between
Georg Brandlbb27c122010-11-11 07:26:40 +0000881 keys and values are surrounded by spaces.
Georg Brandl116aa622007-08-15 14:28:22 +0000882
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Georg Brandlbb27c122010-11-11 07:26:40 +0000884 .. method:: remove_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000885
Georg Brandlbb27c122010-11-11 07:26:40 +0000886 Remove the specified *option* from the specified *section*. If the
887 section does not exist, raise :exc:`NoSectionError`. If the option
888 existed to be removed, return :const:`True`; otherwise return
889 :const:`False`.
Georg Brandl116aa622007-08-15 14:28:22 +0000890
Georg Brandl116aa622007-08-15 14:28:22 +0000891
Georg Brandlbb27c122010-11-11 07:26:40 +0000892 .. method:: remove_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Georg Brandlbb27c122010-11-11 07:26:40 +0000894 Remove the specified *section* from the configuration. If the section in
895 fact existed, return ``True``. Otherwise return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000896
897
Georg Brandlbb27c122010-11-11 07:26:40 +0000898 .. method:: optionxform(option)
Georg Brandl116aa622007-08-15 14:28:22 +0000899
Georg Brandlbb27c122010-11-11 07:26:40 +0000900 Transforms the option name *option* as found in an input file or as passed
901 in by client code to the form that should be used in the internal
902 structures. The default implementation returns a lower-case version of
903 *option*; subclasses may override this or client code can set an attribute
904 of this name on instances to affect this behavior.
Georg Brandl495f7b52009-10-27 15:28:25 +0000905
Fred Drake5a7c11f2010-11-13 05:24:17 +0000906 You don't need to subclass the parser to use this method, you can also
907 set it on an instance, to a function that takes a string argument and
908 returns a string. Setting it to ``str``, for example, would make option
909 names case sensitive::
Georg Brandl495f7b52009-10-27 15:28:25 +0000910
Georg Brandlbb27c122010-11-11 07:26:40 +0000911 cfgparser = ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000912 cfgparser.optionxform = str
Georg Brandl495f7b52009-10-27 15:28:25 +0000913
Georg Brandlbb27c122010-11-11 07:26:40 +0000914 Note that when reading configuration files, whitespace around the option
Fred Drake5a7c11f2010-11-13 05:24:17 +0000915 names is stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000916
Georg Brandl67b21b72010-08-17 15:07:14 +0000917
Georg Brandlbb27c122010-11-11 07:26:40 +0000918 .. method:: readfp(fp, filename=None)
Fred Drakea4923622010-08-09 12:52:45 +0000919
Georg Brandlbb27c122010-11-11 07:26:40 +0000920 .. deprecated:: 3.2
Fred Drake5a7c11f2010-11-13 05:24:17 +0000921 Use :meth:`read_file` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000922
Georg Brandl67b21b72010-08-17 15:07:14 +0000923
Georg Brandl116aa622007-08-15 14:28:22 +0000924.. _configparser-objects:
925
926ConfigParser Objects
927--------------------
928
Łukasz Langa26d513c2010-11-10 18:57:39 +0000929.. warning::
Georg Brandlbb27c122010-11-11 07:26:40 +0000930 Whenever you can, consider using :class:`SafeConfigParser` which adds
931 validation and escaping for the interpolation.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000932
Georg Brandl116aa622007-08-15 14:28:22 +0000933The :class:`ConfigParser` class extends some methods of the
Łukasz Langa26d513c2010-11-10 18:57:39 +0000934:class:`RawConfigParser` interface, adding some optional arguments.
935
936.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
937
938 Derived class of :class:`RawConfigParser` that implements the magical
939 interpolation feature and adds optional arguments to the :meth:`get` and
940 :meth:`items` methods.
941
942 :class:`SafeConfigParser` is generally recommended over this class if you
943 need interpolation.
944
945 The values in *defaults* must be appropriate for the ``%()s`` string
Łukasz Langa5c863392010-11-21 13:41:35 +0000946 interpolation.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000947
948 All option names used in interpolation will be passed through the
949 :meth:`optionxform` method just like any other option name reference. For
950 example, using the default implementation of :meth:`optionxform` (which
951 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
952 %(BAR)s`` are equivalent.
953
954 .. versionchanged:: 3.1
955 The default *dict_type* is :class:`collections.OrderedDict`.
956
957 .. versionchanged:: 3.2
958 *allow_no_value*, *delimiters*, *comment_prefixes*,
959 *strict* and *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961
Georg Brandlbb27c122010-11-11 07:26:40 +0000962 .. method:: get(section, option, raw=False, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Georg Brandlbb27c122010-11-11 07:26:40 +0000964 Get an *option* value for the named *section*. If *vars* is provided, it
965 must be a dictionary. The *option* is looked up in *vars* (if provided),
966 *section*, and in *DEFAULTSECT* in that order. If the key is not found
967 and *fallback* is provided, it is used as a fallback value. ``None`` can
968 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +0000969
Georg Brandlbb27c122010-11-11 07:26:40 +0000970 All the ``'%'`` interpolations are expanded in the return values, unless
971 the *raw* argument is true. Values for interpolation keys are looked up
972 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +0000973
Georg Brandlbb27c122010-11-11 07:26:40 +0000974 .. versionchanged:: 3.2
975 Arguments *raw*, *vars* and *fallback* are keyword only to protect
976 users from trying to use the third argument as the *fallback* fallback
977 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000978
Łukasz Langa26d513c2010-11-10 18:57:39 +0000979
Georg Brandlbb27c122010-11-11 07:26:40 +0000980 .. method:: getint(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000981
Georg Brandlbb27c122010-11-11 07:26:40 +0000982 A convenience method which coerces the *option* in the specified *section*
983 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
984 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000985
986
Georg Brandlbb27c122010-11-11 07:26:40 +0000987 .. method:: getfloat(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000988
Georg Brandlbb27c122010-11-11 07:26:40 +0000989 A convenience method which coerces the *option* in the specified *section*
990 to a floating point number. See :meth:`get` for explanation of *raw*,
991 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000992
993
Georg Brandlbb27c122010-11-11 07:26:40 +0000994 .. method:: getboolean(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000995
Georg Brandlbb27c122010-11-11 07:26:40 +0000996 A convenience method which coerces the *option* in the specified *section*
997 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +0000998 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
999 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001000 cause it to return ``False``. These string values are checked in a
1001 case-insensitive manner. Any other value will cause it to raise
1002 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1003 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001004
1005
Georg Brandlbb27c122010-11-11 07:26:40 +00001006 .. method:: items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001007
Fred Drake5a7c11f2010-11-13 05:24:17 +00001008 Return a list of *name*, *value* pairs for the options in the given
Georg Brandlbb27c122010-11-11 07:26:40 +00001009 *section*. Optional arguments have the same meaning as for the
1010 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001011
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Łukasz Langa26d513c2010-11-10 18:57:39 +00001013.. data:: MAX_INTERPOLATION_DEPTH
1014
1015 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1016 parameter is false. This is relevant only for the :class:`ConfigParser` class.
1017
Georg Brandlbb27c122010-11-11 07:26:40 +00001018
Georg Brandl116aa622007-08-15 14:28:22 +00001019.. _safeconfigparser-objects:
1020
1021SafeConfigParser Objects
1022------------------------
1023
Łukasz Langa26d513c2010-11-10 18:57:39 +00001024.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
1025
Fred Drake5a7c11f2010-11-13 05:24:17 +00001026 Derived class of :class:`ConfigParser` that implements a variant of the
1027 magical interpolation feature. This implementation is more predictable as
1028 it validates the interpolation syntax used within a configuration file.
1029 This class also enables escaping the interpolation character (a key can have
Łukasz Langa26d513c2010-11-10 18:57:39 +00001030 ``%`` as part of the value by specifying ``%%`` in the file).
1031
1032 Applications that don't require interpolation should use
1033 :class:`RawConfigParser`, otherwise :class:`SafeConfigParser` is the best
1034 option.
1035
1036 .. versionchanged:: 3.1
1037 The default *dict_type* is :class:`collections.OrderedDict`.
1038
1039 .. versionchanged:: 3.2
1040 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
1041 *empty_lines_in_values* were added.
1042
1043
Fred Drake5a7c11f2010-11-13 05:24:17 +00001044 The :class:`SafeConfigParser` class implements the same extended interface
1045 as :class:`ConfigParser`, with the following addition:
Georg Brandl116aa622007-08-15 14:28:22 +00001046
Georg Brandlbb27c122010-11-11 07:26:40 +00001047 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001048
Georg Brandlbb27c122010-11-11 07:26:40 +00001049 If the given section exists, set the given option to the specified value;
Fred Drake5a7c11f2010-11-13 05:24:17 +00001050 otherwise raise :exc:`NoSectionError`. *value* must be a string; if not,
1051 :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001052
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001053
Łukasz Langa26d513c2010-11-10 18:57:39 +00001054Exceptions
1055----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001056
Łukasz Langa26d513c2010-11-10 18:57:39 +00001057.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001058
Fred Drake5a7c11f2010-11-13 05:24:17 +00001059 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001060
Georg Brandl48310cd2009-01-03 21:18:54 +00001061
Łukasz Langa26d513c2010-11-10 18:57:39 +00001062.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001063
Łukasz Langa26d513c2010-11-10 18:57:39 +00001064 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001065
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001066
Łukasz Langa26d513c2010-11-10 18:57:39 +00001067.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001068
Łukasz Langa26d513c2010-11-10 18:57:39 +00001069 Exception raised if :meth:`add_section` is called with the name of a section
1070 that is already present or in strict parsers when a section if found more
1071 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001072
Łukasz Langa26d513c2010-11-10 18:57:39 +00001073 .. versionadded:: 3.2
1074 Optional ``source`` and ``lineno`` attributes and arguments to
1075 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001076
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001077
Łukasz Langa26d513c2010-11-10 18:57:39 +00001078.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001079
Łukasz Langa26d513c2010-11-10 18:57:39 +00001080 Exception raised by strict parsers if a single option appears twice during
1081 reading from a single file, string or dictionary. This catches misspellings
1082 and case sensitivity-related errors, e.g. a dictionary may have two keys
1083 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001084
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001085
Łukasz Langa26d513c2010-11-10 18:57:39 +00001086.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001087
Łukasz Langa26d513c2010-11-10 18:57:39 +00001088 Exception raised when a specified option is not found in the specified
1089 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001090
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001091
Łukasz Langa26d513c2010-11-10 18:57:39 +00001092.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001093
Łukasz Langa26d513c2010-11-10 18:57:39 +00001094 Base class for exceptions raised when problems occur performing string
1095 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001096
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001097
Łukasz Langa26d513c2010-11-10 18:57:39 +00001098.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001099
Łukasz Langa26d513c2010-11-10 18:57:39 +00001100 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001101 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001102 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001103
Fred Drake03c44a32010-02-19 06:08:41 +00001104
Łukasz Langa26d513c2010-11-10 18:57:39 +00001105.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001106
Georg Brandlbb27c122010-11-11 07:26:40 +00001107 Exception raised when an option referenced from a value does not exist.
1108 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001109
Fred Drake03c44a32010-02-19 06:08:41 +00001110
Łukasz Langa26d513c2010-11-10 18:57:39 +00001111.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001112
Georg Brandlbb27c122010-11-11 07:26:40 +00001113 Exception raised when the source text into which substitutions are made does
1114 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001115
Łukasz Langa26d513c2010-11-10 18:57:39 +00001116
1117.. exception:: MissingSectionHeaderError
1118
Georg Brandlbb27c122010-11-11 07:26:40 +00001119 Exception raised when attempting to parse a file which has no section
1120 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001121
1122
1123.. exception:: ParsingError
1124
1125 Exception raised when errors occur attempting to parse a file.
1126
1127 .. versionchanged:: 3.2
1128 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1129 ``source`` for consistency.
1130
Georg Brandlbb27c122010-11-11 07:26:40 +00001131
1132.. rubric:: Footnotes
1133
1134.. [1] Config parsers allow for heavy customization. If you are interested in
1135 changing the behaviour outlined by the footnote reference, consult the
1136 `Customizing Parser Behaviour`_ section.