blob: 321770242b003c154180687c7499959bab2c9925 [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
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040014**Source code:** :source:`Lib/configparser.py`
15
Georg Brandl116aa622007-08-15 14:28:22 +000016.. index::
17 pair: .ini; file
18 pair: configuration; file
19 single: ini file
20 single: Windows ini file
21
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040022--------------
23
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000024This module provides the :class:`ConfigParser` class which implements a basic
25configuration language which provides a structure similar to what's found in
26Microsoft Windows INI files. You can use this to write Python programs which
27can be customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000028
Georg Brandle720c0a2009-04-27 16:20:50 +000029.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000030
Georg Brandle720c0a2009-04-27 16:20:50 +000031 This library does *not* interpret or write the value-type prefixes used in
32 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000033
Łukasz Langa26d513c2010-11-10 18:57:39 +000034.. seealso::
35
36 Module :mod:`shlex`
Alex Jordan01fa9ae2017-04-05 22:21:30 -040037 Support for creating Unix shell-like mini-languages which can be used as
38 an alternate format for application configuration files.
Łukasz Langa26d513c2010-11-10 18:57:39 +000039
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000040 Module :mod:`json`
41 The json module implements a subset of JavaScript syntax which can also
42 be used for this purpose.
43
Georg Brandlbb27c122010-11-11 07:26:40 +000044
Marco Buttub2a7c2f2017-03-02 12:02:43 +010045.. testsetup::
46
47 import configparser
48
49
Łukasz Langa26d513c2010-11-10 18:57:39 +000050Quick Start
51-----------
52
Georg Brandlbb27c122010-11-11 07:26:40 +000053Let's take a very basic configuration file that looks like this:
Łukasz Langa26d513c2010-11-10 18:57:39 +000054
Georg Brandlbb27c122010-11-11 07:26:40 +000055.. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +000056
Georg Brandlbb27c122010-11-11 07:26:40 +000057 [DEFAULT]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000058 ServerAliveInterval = 45
59 Compression = yes
60 CompressionLevel = 9
61 ForwardX11 = yes
Łukasz Langa26d513c2010-11-10 18:57:39 +000062
Georg Brandlbb27c122010-11-11 07:26:40 +000063 [bitbucket.org]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000064 User = hg
Łukasz Langa26d513c2010-11-10 18:57:39 +000065
Georg Brandlbb27c122010-11-11 07:26:40 +000066 [topsecret.server.com]
Łukasz Langab6a6f5f2010-12-03 16:28:00 +000067 Port = 50022
68 ForwardX11 = no
Łukasz Langa26d513c2010-11-10 18:57:39 +000069
Fred Drake5a7c11f2010-11-13 05:24:17 +000070The structure of INI files is described `in the following section
71<#supported-ini-file-structure>`_. Essentially, the file
Łukasz Langa26d513c2010-11-10 18:57:39 +000072consists of sections, each of which contains keys with values.
Georg Brandlbb27c122010-11-11 07:26:40 +000073:mod:`configparser` classes can read and write such files. Let's start by
Martin Pantereb995702016-07-28 01:11:04 +000074creating the above configuration file programmatically.
Łukasz Langa26d513c2010-11-10 18:57:39 +000075
Łukasz Langa26d513c2010-11-10 18:57:39 +000076.. doctest::
77
Georg Brandlbb27c122010-11-11 07:26:40 +000078 >>> import configparser
Łukasz Langa7f64c8a2010-12-16 01:16:22 +000079 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +000080 >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
81 ... 'Compression': 'yes',
82 ... 'CompressionLevel': '9'}
83 >>> config['bitbucket.org'] = {}
84 >>> config['bitbucket.org']['User'] = 'hg'
85 >>> config['topsecret.server.com'] = {}
86 >>> topsecret = config['topsecret.server.com']
87 >>> topsecret['Port'] = '50022' # mutates the parser
88 >>> topsecret['ForwardX11'] = 'no' # same here
89 >>> config['DEFAULT']['ForwardX11'] = 'yes'
90 >>> with open('example.ini', 'w') as configfile:
91 ... config.write(configfile)
92 ...
Łukasz Langa26d513c2010-11-10 18:57:39 +000093
Fred Drake5a7c11f2010-11-13 05:24:17 +000094As you can see, we can treat a config parser much like a dictionary.
95There are differences, `outlined later <#mapping-protocol-access>`_, but
96the behavior is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000097
Fred Drake5a7c11f2010-11-13 05:24:17 +000098Now that we have created and saved a configuration file, let's read it
99back and explore the data it holds.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000100
Łukasz Langa26d513c2010-11-10 18:57:39 +0000101.. doctest::
102
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000103 >>> config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000104 >>> config.sections()
105 []
106 >>> config.read('example.ini')
107 ['example.ini']
108 >>> config.sections()
109 ['bitbucket.org', 'topsecret.server.com']
110 >>> 'bitbucket.org' in config
111 True
112 >>> 'bytebong.com' in config
113 False
114 >>> config['bitbucket.org']['User']
115 'hg'
116 >>> config['DEFAULT']['Compression']
117 'yes'
118 >>> topsecret = config['topsecret.server.com']
119 >>> topsecret['ForwardX11']
120 'no'
121 >>> topsecret['Port']
122 '50022'
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100123 >>> for key in config['bitbucket.org']: # doctest: +SKIP
124 ... print(key)
Georg Brandlbb27c122010-11-11 07:26:40 +0000125 user
126 compressionlevel
127 serveraliveinterval
128 compression
129 forwardx11
130 >>> config['bitbucket.org']['ForwardX11']
131 'yes'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000132
Fred Drake5a7c11f2010-11-13 05:24:17 +0000133As we can see above, the API is pretty straightforward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000134involves the ``DEFAULT`` section which provides default values for all other
Fred Drake5a7c11f2010-11-13 05:24:17 +0000135sections [1]_. Note also that keys in sections are
136case-insensitive and stored in lowercase [1]_.
Georg Brandlbb27c122010-11-11 07:26:40 +0000137
Łukasz Langa26d513c2010-11-10 18:57:39 +0000138
139Supported Datatypes
140-------------------
141
142Config parsers do not guess datatypes of values in configuration files, always
Georg Brandlbb27c122010-11-11 07:26:40 +0000143storing them internally as strings. This means that if you need other
144datatypes, you should convert on your own:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000145
Łukasz Langa26d513c2010-11-10 18:57:39 +0000146.. doctest::
147
Georg Brandlbb27c122010-11-11 07:26:40 +0000148 >>> int(topsecret['Port'])
149 50022
150 >>> float(topsecret['CompressionLevel'])
151 9.0
Łukasz Langa26d513c2010-11-10 18:57:39 +0000152
Łukasz Langa34cea142014-09-14 23:37:03 -0700153Since this task is so common, config parsers provide a range of handy getter
154methods to handle integers, floats and booleans. The last one is the most
155interesting because simply passing the value to ``bool()`` would do no good
156since ``bool('False')`` is still ``True``. This is why config parsers also
Jesus Cea647680e2016-09-20 00:01:53 +0200157provide :meth:`~ConfigParser.getboolean`. This method is case-insensitive and
158recognizes Boolean values from ``'yes'``/``'no'``, ``'on'``/``'off'``,
Łukasz Langa34cea142014-09-14 23:37:03 -0700159``'true'``/``'false'`` and ``'1'``/``'0'`` [1]_. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000160
Łukasz Langa26d513c2010-11-10 18:57:39 +0000161.. doctest::
162
Georg Brandlbb27c122010-11-11 07:26:40 +0000163 >>> topsecret.getboolean('ForwardX11')
164 False
165 >>> config['bitbucket.org'].getboolean('ForwardX11')
166 True
167 >>> config.getboolean('bitbucket.org', 'Compression')
168 True
Łukasz Langa26d513c2010-11-10 18:57:39 +0000169
Jesus Cea647680e2016-09-20 00:01:53 +0200170Apart from :meth:`~ConfigParser.getboolean`, config parsers also
171provide equivalent :meth:`~ConfigParser.getint` and
172:meth:`~ConfigParser.getfloat` methods. You can register your own
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700173converters and customize the provided ones. [1]_
Georg Brandlbb27c122010-11-11 07:26:40 +0000174
Łukasz Langa26d513c2010-11-10 18:57:39 +0000175Fallback Values
176---------------
177
Fred Drake5a7c11f2010-11-13 05:24:17 +0000178As with a dictionary, you can use a section's :meth:`get` method to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000179provide fallback values:
180
Łukasz Langa26d513c2010-11-10 18:57:39 +0000181.. doctest::
182
Georg Brandlbb27c122010-11-11 07:26:40 +0000183 >>> topsecret.get('Port')
184 '50022'
185 >>> topsecret.get('CompressionLevel')
186 '9'
187 >>> topsecret.get('Cipher')
188 >>> topsecret.get('Cipher', '3des-cbc')
189 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000190
Fred Drake5a7c11f2010-11-13 05:24:17 +0000191Please note that default values have precedence over fallback values.
192For instance, in our example the ``'CompressionLevel'`` key was
193specified only in the ``'DEFAULT'`` section. If we try to get it from
194the section ``'topsecret.server.com'``, we will always get the default,
195even if we specify a fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000196
Łukasz Langa26d513c2010-11-10 18:57:39 +0000197.. doctest::
198
Georg Brandlbb27c122010-11-11 07:26:40 +0000199 >>> topsecret.get('CompressionLevel', '3')
200 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000201
202One more thing to be aware of is that the parser-level :meth:`get` method
203provides a custom, more complex interface, maintained for backwards
Fred Drake5a7c11f2010-11-13 05:24:17 +0000204compatibility. When using this method, a fallback value can be provided via
205the ``fallback`` keyword-only argument:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000206
Łukasz Langa26d513c2010-11-10 18:57:39 +0000207.. doctest::
208
Georg Brandlbb27c122010-11-11 07:26:40 +0000209 >>> config.get('bitbucket.org', 'monster',
210 ... fallback='No such things as monsters')
211 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000212
Jesus Cea647680e2016-09-20 00:01:53 +0200213The same ``fallback`` argument can be used with the
214:meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat` and
215:meth:`~ConfigParser.getboolean` methods, for example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000216
Łukasz Langa26d513c2010-11-10 18:57:39 +0000217.. doctest::
218
Georg Brandlbb27c122010-11-11 07:26:40 +0000219 >>> 'BatchMode' in topsecret
220 False
221 >>> topsecret.getboolean('BatchMode', fallback=True)
222 True
223 >>> config['DEFAULT']['BatchMode'] = 'no'
224 >>> topsecret.getboolean('BatchMode', fallback=True)
225 False
226
Łukasz Langa26d513c2010-11-10 18:57:39 +0000227
228Supported INI File Structure
229----------------------------
230
Georg Brandl96a60ae2010-07-28 13:13:46 +0000231A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000232followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000233default [1]_). By default, section names are case sensitive but keys are not
Fred Drake5a7c11f2010-11-13 05:24:17 +0000234[1]_. Leading and trailing whitespace is removed from keys and values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000235Values can be omitted, in which case the key/value delimiter may also be left
236out. Values can also span multiple lines, as long as they are indented deeper
237than the first line of the value. Depending on the parser's mode, blank lines
238may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000239
Fred Drake5a7c11f2010-11-13 05:24:17 +0000240Configuration files may include comments, prefixed by specific
241characters (``#`` and ``;`` by default [1]_). Comments may appear on
Łukasz Langab25a7912010-12-17 01:32:29 +0000242their own on an otherwise empty line, possibly indented. [1]_
Georg Brandl96a60ae2010-07-28 13:13:46 +0000243
Georg Brandlbb27c122010-11-11 07:26:40 +0000244For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000245
Georg Brandlbb27c122010-11-11 07:26:40 +0000246.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000248 [Simple Values]
Łukasz Langab25a7912010-12-17 01:32:29 +0000249 key=value
250 spaces in keys=allowed
251 spaces in values=allowed as well
252 spaces around the delimiter = obviously
253 you can also use : to delimit keys from values
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000254
255 [All Values Are Strings]
256 values like this: 1000000
257 or this: 3.14159265359
258 are they treated as numbers? : no
259 integers, floats and booleans are held as: strings
260 can use the API to get converted values directly: true
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Georg Brandl96a60ae2010-07-28 13:13:46 +0000262 [Multiline Values]
263 chorus: I'm a lumberjack, and I'm okay
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000264 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000265
Georg Brandl96a60ae2010-07-28 13:13:46 +0000266 [No Values]
267 key_without_value
268 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Łukasz Langab25a7912010-12-17 01:32:29 +0000270 [You can use comments]
271 # like this
272 ; or this
273
274 # By default only in an empty line.
275 # Inline comments can be harmful because they prevent users
276 # from using the delimiting characters as parts of values.
277 # That being said, this can be customized.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000278
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000279 [Sections Can Be Indented]
280 can_values_be_as_well = True
281 does_that_mean_anything_special = False
282 purpose = formatting for readability
283 multiline_values = are
284 handled just fine as
285 long as they are indented
286 deeper than the first line
287 of a value
288 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000289
Georg Brandl96a60ae2010-07-28 13:13:46 +0000290
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000291Interpolation of values
292-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000293
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000294On top of the core functionality, :class:`ConfigParser` supports
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000295interpolation. This means values can be preprocessed before returning them
296from ``get()`` calls.
297
Miss Islington (bot)fdf48b62018-10-28 09:43:32 -0700298.. index:: single: % (percent); interpolation in configuration files
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300299
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000300.. class:: BasicInterpolation()
301
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000302 The default implementation used by :class:`ConfigParser`. It enables
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000303 values to contain format strings which refer to other values in the same
304 section, or values in the special default section [1]_. Additional default
305 values can be provided on initialization.
306
307 For example:
308
309 .. code-block:: ini
310
311 [Paths]
312 home_dir: /Users
313 my_dir: %(home_dir)s/lumberjack
314 my_pictures: %(my_dir)s/Pictures
315
316
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000317 In the example above, :class:`ConfigParser` with *interpolation* set to
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000318 ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
319 ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in effect would
320 resolve to ``/Users/lumberjack``. All interpolations are done on demand so
321 keys used in the chain of references do not have to be specified in any
322 specific order in the configuration file.
323
324 With ``interpolation`` set to ``None``, the parser would simply return
325 ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
326 ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
327
Miss Islington (bot)fdf48b62018-10-28 09:43:32 -0700328.. index:: single: $ (dollar); interpolation in configuration files
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300329
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000330.. class:: ExtendedInterpolation()
331
332 An alternative handler for interpolation which implements a more advanced
Łukasz Langa34cea142014-09-14 23:37:03 -0700333 syntax, used for instance in ``zc.buildout``. Extended interpolation is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000334 using ``${section:option}`` to denote a value from a foreign section.
Łukasz Langa34cea142014-09-14 23:37:03 -0700335 Interpolation can span multiple levels. For convenience, if the
336 ``section:`` part is omitted, interpolation defaults to the current section
337 (and possibly the default values from the special section).
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000338
339 For example, the configuration specified above with basic interpolation,
340 would look like this with extended interpolation:
341
342 .. code-block:: ini
343
344 [Paths]
345 home_dir: /Users
346 my_dir: ${home_dir}/lumberjack
347 my_pictures: ${my_dir}/Pictures
348
349 Values from other sections can be fetched as well:
350
351 .. code-block:: ini
352
353 [Common]
354 home_dir: /Users
355 library_dir: /Library
356 system_dir: /System
357 macports_dir: /opt/local
358
359 [Frameworks]
360 Python: 3.2
361 path: ${Common:system_dir}/Library/Frameworks/
362
363 [Arthur]
364 nickname: Two Sheds
365 last_name: Jackson
366 my_dir: ${Common:home_dir}/twosheds
367 my_pictures: ${my_dir}/Pictures
368 python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Georg Brandlbb27c122010-11-11 07:26:40 +0000369
Łukasz Langa26d513c2010-11-10 18:57:39 +0000370Mapping Protocol Access
371-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000372
Łukasz Langa26d513c2010-11-10 18:57:39 +0000373.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000374
Łukasz Langa26d513c2010-11-10 18:57:39 +0000375Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000376custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000377the mapping interface implementation is using the
378``parser['section']['option']`` notation.
379
380``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000381the parser. This means that the values are not copied but they are taken from
382the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000383are changed on a section proxy, they are actually mutated in the original
384parser.
385
386:mod:`configparser` objects behave as close to actual dictionaries as possible.
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300387The mapping interface is complete and adheres to the
388:class:`~collections.abc.MutableMapping` ABC.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000389However, there are a few differences that should be taken into account:
390
Georg Brandlbb27c122010-11-11 07:26:40 +0000391* By default, all keys in sections are accessible in a case-insensitive manner
392 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
393 option key names. This means lowercased keys by default. At the same time,
Fred Drake5a7c11f2010-11-13 05:24:17 +0000394 for a section that holds the key ``'a'``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000395
Georg Brandlbb27c122010-11-11 07:26:40 +0000396 "a" in parser["section"]
397 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000398
Georg Brandlbb27c122010-11-11 07:26:40 +0000399* All sections include ``DEFAULTSECT`` values as well which means that
400 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000401 because default values cannot be deleted from the section (because technically
Donald Stufft8b852f12014-05-20 12:58:38 -0400402 they are not there). If they are overridden in the section, deleting causes
Georg Brandlbb27c122010-11-11 07:26:40 +0000403 the default value to be visible again. Trying to delete a default value
Miss Islington (bot)ec10b702018-10-26 03:56:28 -0700404 causes a :exc:`KeyError`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000405
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100406* ``DEFAULTSECT`` cannot be removed from the parser:
407
Miss Islington (bot)ec10b702018-10-26 03:56:28 -0700408 * trying to delete it raises :exc:`ValueError`,
Łukasz Langa3a8479a2012-12-31 03:38:39 +0100409
410 * ``parser.clear()`` leaves it intact,
411
412 * ``parser.popitem()`` never returns it.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000413
Łukasz Langa71b37a52010-12-17 21:56:32 +0000414* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
Łukasz Langa34cea142014-09-14 23:37:03 -0700415 a fallback value. Note however that the section-level ``get()`` methods are
Łukasz Langa71b37a52010-12-17 21:56:32 +0000416 compatible both with the mapping protocol and the classic configparser API.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000417
Łukasz Langa71b37a52010-12-17 21:56:32 +0000418* ``parser.items()`` is compatible with the mapping protocol (returns a list of
419 *section_name*, *section_proxy* pairs including the DEFAULTSECT). However,
420 this method can also be invoked with arguments: ``parser.items(section, raw,
Łukasz Langa34cea142014-09-14 23:37:03 -0700421 vars)``. The latter call returns a list of *option*, *value* pairs for
Łukasz Langa71b37a52010-12-17 21:56:32 +0000422 a specified ``section``, with all interpolations expanded (unless
423 ``raw=True`` is provided).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000424
425The mapping protocol is implemented on top of the existing legacy API so that
Łukasz Langa71b37a52010-12-17 21:56:32 +0000426subclasses overriding the original interface still should have mappings working
427as expected.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000428
Georg Brandlbb27c122010-11-11 07:26:40 +0000429
Łukasz Langa26d513c2010-11-10 18:57:39 +0000430Customizing Parser Behaviour
431----------------------------
432
433There are nearly as many INI format variants as there are applications using it.
434:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000435set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000436historical background and it's very likely that you will want to customize some
437of the features.
438
Fred Drake5a7c11f2010-11-13 05:24:17 +0000439The most common way to change the way a specific config parser works is to use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000440the :meth:`__init__` options:
441
442* *defaults*, default value: ``None``
443
444 This option accepts a dictionary of key-value pairs which will be initially
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000445 put in the ``DEFAULT`` section. This makes for an elegant way to support
446 concise configuration files that don't specify values which are the same as
447 the documented default.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000448
Fred Drake5a7c11f2010-11-13 05:24:17 +0000449 Hint: if you want to specify default values for a specific section, use
Łukasz Langa26d513c2010-11-10 18:57:39 +0000450 :meth:`read_dict` before you read the actual file.
451
452* *dict_type*, default value: :class:`collections.OrderedDict`
453
454 This option has a major impact on how the mapping protocol will behave and how
Fred Drake5a7c11f2010-11-13 05:24:17 +0000455 the written configuration files look. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000456 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000457 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000458
459 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000460 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000461 reasons.
462
463 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000464 operation. When you use a regular dictionary in those operations, the order
465 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000466
Łukasz Langa26d513c2010-11-10 18:57:39 +0000467 .. doctest::
468
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000469 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000470 >>> parser.read_dict({'section1': {'key1': 'value1',
471 ... 'key2': 'value2',
472 ... 'key3': 'value3'},
473 ... 'section2': {'keyA': 'valueA',
474 ... 'keyB': 'valueB',
475 ... 'keyC': 'valueC'},
476 ... 'section3': {'foo': 'x',
477 ... 'bar': 'y',
478 ... 'baz': 'z'}
479 ... })
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100480 >>> parser.sections() # doctest: +SKIP
Georg Brandlbb27c122010-11-11 07:26:40 +0000481 ['section3', 'section2', 'section1']
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100482 >>> [option for option in parser['section3']] # doctest: +SKIP
Georg Brandlbb27c122010-11-11 07:26:40 +0000483 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000484
485 In these operations you need to use an ordered dictionary as well:
486
Łukasz Langa26d513c2010-11-10 18:57:39 +0000487 .. doctest::
488
Georg Brandlbb27c122010-11-11 07:26:40 +0000489 >>> from collections import OrderedDict
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000490 >>> parser = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000491 >>> parser.read_dict(
492 ... OrderedDict((
493 ... ('s1',
494 ... OrderedDict((
495 ... ('1', '2'),
496 ... ('3', '4'),
497 ... ('5', '6'),
498 ... ))
499 ... ),
500 ... ('s2',
501 ... OrderedDict((
502 ... ('a', 'b'),
503 ... ('c', 'd'),
504 ... ('e', 'f'),
505 ... ))
506 ... ),
507 ... ))
508 ... )
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100509 >>> parser.sections() # doctest: +SKIP
Georg Brandlbb27c122010-11-11 07:26:40 +0000510 ['s1', 's2']
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100511 >>> [option for option in parser['s1']] # doctest: +SKIP
Georg Brandlbb27c122010-11-11 07:26:40 +0000512 ['1', '3', '5']
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100513 >>> [option for option in parser['s2'].values()] # doctest: +SKIP
Georg Brandlbb27c122010-11-11 07:26:40 +0000514 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000515
516* *allow_no_value*, default value: ``False``
517
518 Some configuration files are known to include settings without values, but
519 which otherwise conform to the syntax supported by :mod:`configparser`. The
Fred Drake5a7c11f2010-11-13 05:24:17 +0000520 *allow_no_value* parameter to the constructor can be used to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000521 indicate that such values should be accepted:
522
Łukasz Langa26d513c2010-11-10 18:57:39 +0000523 .. doctest::
524
Georg Brandlbb27c122010-11-11 07:26:40 +0000525 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000526
Georg Brandlbb27c122010-11-11 07:26:40 +0000527 >>> sample_config = """
528 ... [mysqld]
529 ... user = mysql
530 ... pid-file = /var/run/mysqld/mysqld.pid
531 ... skip-external-locking
532 ... old_passwords = 1
533 ... skip-bdb
Łukasz Langab25a7912010-12-17 01:32:29 +0000534 ... # we don't need ACID today
535 ... skip-innodb
Georg Brandlbb27c122010-11-11 07:26:40 +0000536 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000537 >>> config = configparser.ConfigParser(allow_no_value=True)
Georg Brandlbb27c122010-11-11 07:26:40 +0000538 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000539
Georg Brandlbb27c122010-11-11 07:26:40 +0000540 >>> # Settings with values are treated as before:
541 >>> config["mysqld"]["user"]
542 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000543
Georg Brandlbb27c122010-11-11 07:26:40 +0000544 >>> # Settings without values provide None:
545 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000546
Georg Brandlbb27c122010-11-11 07:26:40 +0000547 >>> # Settings which aren't specified still raise an error:
548 >>> config["mysqld"]["does-not-exist"]
549 Traceback (most recent call last):
550 ...
551 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000552
553* *delimiters*, default value: ``('=', ':')``
554
Łukasz Langa34cea142014-09-14 23:37:03 -0700555 Delimiters are substrings that delimit keys from values within a section.
556 The first occurrence of a delimiting substring on a line is considered
557 a delimiter. This means values (but not keys) can contain the delimiters.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000558
559 See also the *space_around_delimiters* argument to
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000560 :meth:`ConfigParser.write`.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000561
Łukasz Langab25a7912010-12-17 01:32:29 +0000562* *comment_prefixes*, default value: ``('#', ';')``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000563
Łukasz Langab25a7912010-12-17 01:32:29 +0000564* *inline_comment_prefixes*, default value: ``None``
565
566 Comment prefixes are strings that indicate the start of a valid comment within
567 a config file. *comment_prefixes* are used only on otherwise empty lines
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700568 (optionally indented) whereas *inline_comment_prefixes* can be used after
569 every valid value (e.g. section names, options and empty lines as well). By
570 default inline comments are disabled and ``'#'`` and ``';'`` are used as
571 prefixes for whole line comments.
Łukasz Langab25a7912010-12-17 01:32:29 +0000572
573 .. versionchanged:: 3.2
574 In previous versions of :mod:`configparser` behaviour matched
575 ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000576
577 Please note that config parsers don't support escaping of comment prefixes so
Łukasz Langab25a7912010-12-17 01:32:29 +0000578 using *inline_comment_prefixes* may prevent users from specifying option
Łukasz Langa34cea142014-09-14 23:37:03 -0700579 values with characters used as comment prefixes. When in doubt, avoid
580 setting *inline_comment_prefixes*. In any circumstances, the only way of
581 storing comment prefix characters at the beginning of a line in multiline
582 values is to interpolate the prefix, for example::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000583
Łukasz Langab25a7912010-12-17 01:32:29 +0000584 >>> from configparser import ConfigParser, ExtendedInterpolation
585 >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
586 >>> # the default BasicInterpolation could be used as well
587 >>> parser.read_string("""
588 ... [DEFAULT]
589 ... hash = #
590 ...
591 ... [hashes]
592 ... shebang =
593 ... ${hash}!/usr/bin/env python
594 ... ${hash} -*- coding: utf-8 -*-
595 ...
596 ... extensions =
597 ... enabled_extension
598 ... another_extension
599 ... #disabled_by_comment
600 ... yet_another_extension
601 ...
602 ... interpolation not necessary = if # is not at line start
603 ... even in multiline values = line #1
604 ... line #2
605 ... line #3
606 ... """)
607 >>> print(parser['hashes']['shebang'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100608 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000609 #!/usr/bin/env python
610 # -*- coding: utf-8 -*-
611 >>> print(parser['hashes']['extensions'])
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100612 <BLANKLINE>
Łukasz Langab25a7912010-12-17 01:32:29 +0000613 enabled_extension
614 another_extension
615 yet_another_extension
616 >>> print(parser['hashes']['interpolation not necessary'])
617 if # is not at line start
618 >>> print(parser['hashes']['even in multiline values'])
619 line #1
620 line #2
621 line #3
622
623* *strict*, default value: ``True``
624
625 When set to ``True``, the parser will not allow for any section or option
Łukasz Langa26d513c2010-11-10 18:57:39 +0000626 duplicates while reading from a single source (using :meth:`read_file`,
Łukasz Langa34cea142014-09-14 23:37:03 -0700627 :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000628 parsers in new applications.
629
Łukasz Langab25a7912010-12-17 01:32:29 +0000630 .. versionchanged:: 3.2
631 In previous versions of :mod:`configparser` behaviour matched
632 ``strict=False``.
633
Łukasz Langa26d513c2010-11-10 18:57:39 +0000634* *empty_lines_in_values*, default value: ``True``
635
Fred Drake5a7c11f2010-11-13 05:24:17 +0000636 In config parsers, values can span multiple lines as long as they are
637 indented more than the key that holds them. By default parsers also let
638 empty lines to be parts of values. At the same time, keys can be arbitrarily
639 indented themselves to improve readability. In consequence, when
640 configuration files get big and complex, it is easy for the user to lose
641 track of the file structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000642
Georg Brandlbb27c122010-11-11 07:26:40 +0000643 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000644
Georg Brandlbb27c122010-11-11 07:26:40 +0000645 [Section]
646 key = multiline
647 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000648
Georg Brandlbb27c122010-11-11 07:26:40 +0000649 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000650
Georg Brandlbb27c122010-11-11 07:26:40 +0000651 This can be especially problematic for the user to see if she's using a
652 proportional font to edit the file. That is why when your application does
653 not need values with empty lines, you should consider disallowing them. This
654 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000655 produce two keys, ``key`` and ``this``.
656
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000657* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
658 ``"DEFAULT"``)
659
660 The convention of allowing a special section of default values for other
661 sections or interpolation purposes is a powerful concept of this library,
Łukasz Langa34cea142014-09-14 23:37:03 -0700662 letting users create complex declarative configurations. This section is
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000663 normally called ``"DEFAULT"`` but this can be customized to point to any
Łukasz Langa34cea142014-09-14 23:37:03 -0700664 other valid section name. Some typical values include: ``"general"`` or
665 ``"common"``. The name provided is used for recognizing default sections
666 when reading from any source and is used when writing configuration back to
667 a file. Its current value can be retrieved using the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000668 ``parser_instance.default_section`` attribute and may be modified at runtime
669 (i.e. to convert files from one format to another).
670
671* *interpolation*, default value: ``configparser.BasicInterpolation``
672
673 Interpolation behaviour may be customized by providing a custom handler
674 through the *interpolation* argument. ``None`` can be used to turn off
675 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700676 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000677 `dedicated documentation section <#interpolation-of-values>`_.
Łukasz Langab25a7912010-12-17 01:32:29 +0000678 :class:`RawConfigParser` has a default value of ``None``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000679
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700680* *converters*, default value: not set
681
682 Config parsers provide option value getters that perform type conversion. By
Jesus Cea647680e2016-09-20 00:01:53 +0200683 default :meth:`~ConfigParser.getint`, :meth:`~ConfigParser.getfloat`, and
684 :meth:`~ConfigParser.getboolean` are implemented. Should other getters be
685 desirable, users may define them in a subclass or pass a dictionary where each
686 key is a name of the converter and each value is a callable implementing said
687 conversion. For instance, passing ``{'decimal': decimal.Decimal}`` would add
688 :meth:`getdecimal` on both the parser object and all section proxies. In
689 other words, it will be possible to write both
690 ``parser_instance.getdecimal('section', 'key', fallback=0)`` and
691 ``parser_instance['section'].getdecimal('key', 0)``.
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700692
693 If the converter needs to access the state of the parser, it can be
694 implemented as a method on a config parser subclass. If the name of this
695 method starts with ``get``, it will be available on all section proxies, in
696 the dict-compatible form (see the ``getdecimal()`` example above).
Łukasz Langa26d513c2010-11-10 18:57:39 +0000697
Fred Drake5a7c11f2010-11-13 05:24:17 +0000698More advanced customization may be achieved by overriding default values of
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700699these parser attributes. The defaults are defined on the classes, so they may
700be overridden by subclasses or by attribute assignment.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000701
Miss Islington (bot)b3223942018-10-24 16:56:25 -0700702.. attribute:: ConfigParser.BOOLEAN_STATES
Łukasz Langa26d513c2010-11-10 18:57:39 +0000703
Jesus Cea647680e2016-09-20 00:01:53 +0200704 By default when using :meth:`~ConfigParser.getboolean`, config parsers
705 consider the following values ``True``: ``'1'``, ``'yes'``, ``'true'``,
706 ``'on'`` and the following values ``False``: ``'0'``, ``'no'``, ``'false'``,
707 ``'off'``. You can override this by specifying a custom dictionary of strings
708 and their Boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000709
Łukasz Langa26d513c2010-11-10 18:57:39 +0000710 .. doctest::
711
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000712 >>> custom = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000713 >>> custom['section1'] = {'funky': 'nope'}
714 >>> custom['section1'].getboolean('funky')
715 Traceback (most recent call last):
716 ...
717 ValueError: Not a boolean: nope
718 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
719 >>> custom['section1'].getboolean('funky')
720 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000721
Fred Drake5a7c11f2010-11-13 05:24:17 +0000722 Other typical Boolean pairs include ``accept``/``reject`` or
Łukasz Langa26d513c2010-11-10 18:57:39 +0000723 ``enabled``/``disabled``.
724
Miss Islington (bot)b3223942018-10-24 16:56:25 -0700725.. method:: ConfigParser.optionxform(option)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000726
Fred Drake5a7c11f2010-11-13 05:24:17 +0000727 This method transforms option names on every read, get, or set
728 operation. The default converts the name to lowercase. This also
729 means that when a configuration file gets written, all keys will be
730 lowercase. Override this method if that's unsuitable.
731 For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000732
Łukasz Langa26d513c2010-11-10 18:57:39 +0000733 .. doctest::
734
Georg Brandlbb27c122010-11-11 07:26:40 +0000735 >>> config = """
736 ... [Section1]
737 ... Key = Value
738 ...
739 ... [Section2]
740 ... AnotherKey = Value
741 ... """
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000742 >>> typical = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +0000743 >>> typical.read_string(config)
744 >>> list(typical['Section1'].keys())
745 ['key']
746 >>> list(typical['Section2'].keys())
747 ['anotherkey']
748 >>> custom = configparser.RawConfigParser()
749 >>> custom.optionxform = lambda option: option
750 >>> custom.read_string(config)
751 >>> list(custom['Section1'].keys())
752 ['Key']
753 >>> list(custom['Section2'].keys())
754 ['AnotherKey']
755
Miss Islington (bot)b3223942018-10-24 16:56:25 -0700756.. attribute:: ConfigParser.SECTCRE
Łukasz Langa66c908e2011-01-28 11:57:30 +0000757
Łukasz Langa34cea142014-09-14 23:37:03 -0700758 A compiled regular expression used to parse section headers. The default
759 matches ``[section]`` to the name ``"section"``. Whitespace is considered
760 part of the section name, thus ``[ larch ]`` will be read as a section of
761 name ``" larch "``. Override this attribute if that's unsuitable. For
762 example:
Łukasz Langa66c908e2011-01-28 11:57:30 +0000763
764 .. doctest::
765
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100766 >>> import re
Łukasz Langa66c908e2011-01-28 11:57:30 +0000767 >>> config = """
768 ... [Section 1]
769 ... option = value
770 ...
771 ... [ Section 2 ]
772 ... another = val
773 ... """
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100774 >>> typical = configparser.ConfigParser()
Łukasz Langa66c908e2011-01-28 11:57:30 +0000775 >>> typical.read_string(config)
776 >>> typical.sections()
777 ['Section 1', ' Section 2 ']
Marco Buttub2a7c2f2017-03-02 12:02:43 +0100778 >>> custom = configparser.ConfigParser()
Łukasz Langa66c908e2011-01-28 11:57:30 +0000779 >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
780 >>> custom.read_string(config)
781 >>> custom.sections()
782 ['Section 1', 'Section 2']
783
784 .. note::
785
786 While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
787 option lines, it's not recommended to override it because that would
788 interfere with constructor options *allow_no_value* and *delimiters*.
789
Łukasz Langa26d513c2010-11-10 18:57:39 +0000790
791Legacy API Examples
792-------------------
793
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000794Mainly because of backwards compatibility concerns, :mod:`configparser`
795provides also a legacy API with explicit ``get``/``set`` methods. While there
796are valid use cases for the methods outlined below, mapping protocol access is
797preferred for new projects. The legacy API is at times more advanced,
798low-level and downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000799
800An example of writing to a configuration file::
801
802 import configparser
803
804 config = configparser.RawConfigParser()
805
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000806 # Please note that using RawConfigParser's set functions, you can assign
807 # non-string values to keys internally, but will receive an error when
808 # attempting to write to a file or when you get it in non-raw mode. Setting
809 # values using the mapping protocol or ConfigParser's set() does not allow
810 # such assignments to take place.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000811 config.add_section('Section1')
R David Murray1a1883d2012-09-29 14:40:23 -0400812 config.set('Section1', 'an_int', '15')
813 config.set('Section1', 'a_bool', 'true')
814 config.set('Section1', 'a_float', '3.1415')
Łukasz Langa26d513c2010-11-10 18:57:39 +0000815 config.set('Section1', 'baz', 'fun')
816 config.set('Section1', 'bar', 'Python')
817 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
818
819 # Writing our configuration file to 'example.cfg'
820 with open('example.cfg', 'w') as configfile:
821 config.write(configfile)
822
823An example of reading the configuration file again::
824
825 import configparser
826
827 config = configparser.RawConfigParser()
828 config.read('example.cfg')
829
830 # getfloat() raises an exception if the value is not a float
831 # getint() and getboolean() also do this for their respective types
R David Murray1a1883d2012-09-29 14:40:23 -0400832 a_float = config.getfloat('Section1', 'a_float')
833 an_int = config.getint('Section1', 'an_int')
834 print(a_float + an_int)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000835
836 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
837 # This is because we are using a RawConfigParser().
R David Murray1a1883d2012-09-29 14:40:23 -0400838 if config.getboolean('Section1', 'a_bool'):
Łukasz Langa26d513c2010-11-10 18:57:39 +0000839 print(config.get('Section1', 'foo'))
840
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000841To get interpolation, use :class:`ConfigParser`::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000842
843 import configparser
844
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000845 cfg = configparser.ConfigParser()
Łukasz Langa26d513c2010-11-10 18:57:39 +0000846 cfg.read('example.cfg')
847
Éric Araujo941afed2011-09-01 02:47:34 +0200848 # Set the optional *raw* argument of get() to True if you wish to disable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000849 # interpolation in a single get operation.
Serhiy Storchakadba90392016-05-10 12:01:23 +0300850 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
851 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000852
Éric Araujo941afed2011-09-01 02:47:34 +0200853 # The optional *vars* argument is a dict with members that will take
Łukasz Langa26d513c2010-11-10 18:57:39 +0000854 # precedence in interpolation.
855 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
Serhiy Storchakadba90392016-05-10 12:01:23 +0300856 'baz': 'evil'}))
Łukasz Langa26d513c2010-11-10 18:57:39 +0000857
Éric Araujo941afed2011-09-01 02:47:34 +0200858 # The optional *fallback* argument can be used to provide a fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000859 print(cfg.get('Section1', 'foo'))
860 # -> "Python is fun!"
861
862 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
863 # -> "Python is fun!"
864
865 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
866 # -> "No such things as monsters."
867
868 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
869 # but we can also use:
870
871 print(cfg.get('Section1', 'monster', fallback=None))
872 # -> None
873
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000874Default values are available in both types of ConfigParsers. They are used in
875interpolation if an option used is not defined elsewhere. ::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000876
877 import configparser
878
879 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000880 config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
Łukasz Langa26d513c2010-11-10 18:57:39 +0000881 config.read('example.cfg')
882
Serhiy Storchakadba90392016-05-10 12:01:23 +0300883 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000884 config.remove_option('Section1', 'bar')
885 config.remove_option('Section1', 'baz')
Serhiy Storchakadba90392016-05-10 12:01:23 +0300886 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Łukasz Langa26d513c2010-11-10 18:57:39 +0000887
Georg Brandlbb27c122010-11-11 07:26:40 +0000888
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000889.. _configparser-objects:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000890
Łukasz Langa7f64c8a2010-12-16 01:16:22 +0000891ConfigParser Objects
892--------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000893
Miss Islington (bot)dc20d9d2018-06-08 12:26:07 -0700894.. class:: ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})
Georg Brandl116aa622007-08-15 14:28:22 +0000895
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000896 The main configuration parser. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000897 into the dictionary of intrinsic defaults. When *dict_type* is given, it
898 will be used to create the dictionary objects for the list of sections, for
899 the options within a section, and for the default values.
900
Fred Drake5a7c11f2010-11-13 05:24:17 +0000901 When *delimiters* is given, it is used as the set of substrings that
Georg Brandl96a60ae2010-07-28 13:13:46 +0000902 divide keys from values. When *comment_prefixes* is given, it will be used
Łukasz Langab25a7912010-12-17 01:32:29 +0000903 as the set of substrings that prefix comments in otherwise empty lines.
Łukasz Langa34cea142014-09-14 23:37:03 -0700904 Comments can be indented. When *inline_comment_prefixes* is given, it will
905 be used as the set of substrings that prefix comments in non-empty lines.
Łukasz Langab25a7912010-12-17 01:32:29 +0000906
Łukasz Langab25a7912010-12-17 01:32:29 +0000907 When *strict* is ``True`` (the default), the parser won't allow for
Fred Drakea4923622010-08-09 12:52:45 +0000908 any section or option duplicates while reading from a single source (file,
909 string or dictionary), raising :exc:`DuplicateSectionError` or
Fred Drake5a7c11f2010-11-13 05:24:17 +0000910 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
Fred Drakea4923622010-08-09 12:52:45 +0000911 (default: ``True``), each empty line marks the end of an option. Otherwise,
912 internal empty lines of a multiline option are kept as part of the value.
913 When *allow_no_value* is ``True`` (default: ``False``), options without
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000914 values are accepted; the value held for these is ``None`` and they are
915 serialized without the trailing delimiter.
Fred Drake03c44a32010-02-19 06:08:41 +0000916
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000917 When *default_section* is given, it specifies the name for the special
918 section holding default values for other sections and interpolation purposes
Łukasz Langa34cea142014-09-14 23:37:03 -0700919 (normally named ``"DEFAULT"``). This value can be retrieved and changed on
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000920 runtime using the ``default_section`` instance attribute.
921
922 Interpolation behaviour may be customized by providing a custom handler
923 through the *interpolation* argument. ``None`` can be used to turn off
924 interpolation completely, ``ExtendedInterpolation()`` provides a more
Łukasz Langa34cea142014-09-14 23:37:03 -0700925 advanced variant inspired by ``zc.buildout``. More on the subject in the
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000926 `dedicated documentation section <#interpolation-of-values>`_.
927
928 All option names used in interpolation will be passed through the
929 :meth:`optionxform` method just like any other option name reference. For
930 example, using the default implementation of :meth:`optionxform` (which
931 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
932 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000933
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700934 When *converters* is given, it should be a dictionary where each key
935 represents the name of a type converter and each value is a callable
936 implementing the conversion from string to the desired datatype. Every
937 converter gets its own corresponding :meth:`get*()` method on the parser
938 object and section proxies.
939
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000940 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000941 The default *dict_type* is :class:`collections.OrderedDict`.
942
Fred Drake03c44a32010-02-19 06:08:41 +0000943 .. versionchanged:: 3.2
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000944 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
945 *empty_lines_in_values*, *default_section* and *interpolation* were
946 added.
Georg Brandl116aa622007-08-15 14:28:22 +0000947
Łukasz Langadfdd2f72014-09-15 02:08:41 -0700948 .. versionchanged:: 3.5
949 The *converters* argument was added.
950
Łukasz Langaea579232017-08-21 16:23:38 -0700951 .. versionchanged:: 3.7
952 The *defaults* argument is read with :meth:`read_dict()`,
953 providing consistent behavior across the parser: non-string
954 keys and values are implicitly converted to strings.
955
Miss Islington (bot)dc20d9d2018-06-08 12:26:07 -0700956 .. versionchanged:: 3.7
957 The default *dict_type* is :class:`dict`, since it now preserves
958 insertion order.
Fred Drake03c44a32010-02-19 06:08:41 +0000959
Georg Brandlbb27c122010-11-11 07:26:40 +0000960 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000961
Georg Brandlbb27c122010-11-11 07:26:40 +0000962 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964
Georg Brandlbb27c122010-11-11 07:26:40 +0000965 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000967 Return a list of the sections available; the *default section* is not
968 included in the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000969
970
Georg Brandlbb27c122010-11-11 07:26:40 +0000971 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000972
Georg Brandlbb27c122010-11-11 07:26:40 +0000973 Add a section named *section* to the instance. If a section by the given
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000974 name already exists, :exc:`DuplicateSectionError` is raised. If the
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +0000975 *default section* name is passed, :exc:`ValueError` is raised. The name
976 of the section must be a string; if not, :exc:`TypeError` is raised.
977
978 .. versionchanged:: 3.2
979 Non-string section names raise :exc:`TypeError`.
Georg Brandl116aa622007-08-15 14:28:22 +0000980
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Georg Brandlbb27c122010-11-11 07:26:40 +0000982 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000983
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000984 Indicates whether the named *section* is present in the configuration.
985 The *default section* is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000986
Georg Brandl116aa622007-08-15 14:28:22 +0000987
Georg Brandlbb27c122010-11-11 07:26:40 +0000988 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000989
Georg Brandlbb27c122010-11-11 07:26:40 +0000990 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000991
Georg Brandl116aa622007-08-15 14:28:22 +0000992
Georg Brandlbb27c122010-11-11 07:26:40 +0000993 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000994
Łukasz Langab6a6f5f2010-12-03 16:28:00 +0000995 If the given *section* exists, and contains the given *option*, return
Łukasz Langa34cea142014-09-14 23:37:03 -0700996 :const:`True`; otherwise return :const:`False`. If the specified
Łukasz Langa71b37a52010-12-17 21:56:32 +0000997 *section* is :const:`None` or an empty string, DEFAULT is assumed.
Georg Brandl116aa622007-08-15 14:28:22 +0000998
Georg Brandl116aa622007-08-15 14:28:22 +0000999
Georg Brandlbb27c122010-11-11 07:26:40 +00001000 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001001
Miss Islington (bot)b0b8f9b2018-09-29 09:33:05 -07001002 Attempt to read and parse an iterable of filenames, returning a list of
David Ellis85b8d012017-03-03 17:14:27 +00001003 filenames which were successfully parsed.
1004
Vincent Michele3148532017-11-02 13:47:04 +01001005 If *filenames* is a string, a :class:`bytes` object or a
1006 :term:`path-like object`, it is treated as
David Ellis85b8d012017-03-03 17:14:27 +00001007 a single filename. If a file named in *filenames* cannot be opened, that
Miss Islington (bot)b0b8f9b2018-09-29 09:33:05 -07001008 file will be ignored. This is designed so that you can specify an
1009 iterable of potential configuration file locations (for example, the
1010 current directory, the user's home directory, and some system-wide
1011 directory), and all existing configuration files in the iterable will be
1012 read.
David Ellis85b8d012017-03-03 17:14:27 +00001013
1014 If none of the named files exist, the :class:`ConfigParser`
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001015 instance will contain an empty dataset. An application which requires
1016 initial values to be loaded from a file should load the required file or
1017 files using :meth:`read_file` before calling :meth:`read` for any
1018 optional files::
Georg Brandl116aa622007-08-15 14:28:22 +00001019
Georg Brandlbb27c122010-11-11 07:26:40 +00001020 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +00001021
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001022 config = configparser.ConfigParser()
Georg Brandlbb27c122010-11-11 07:26:40 +00001023 config.read_file(open('defaults.cfg'))
1024 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
1025 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +00001026
Georg Brandlbb27c122010-11-11 07:26:40 +00001027 .. versionadded:: 3.2
1028 The *encoding* parameter. Previously, all files were read using the
1029 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +00001030
David Ellis85b8d012017-03-03 17:14:27 +00001031 .. versionadded:: 3.6.1
1032 The *filenames* parameter accepts a :term:`path-like object`.
1033
Vincent Michele3148532017-11-02 13:47:04 +01001034 .. versionadded:: 3.7
1035 The *filenames* parameter accepts a :class:`bytes` object.
1036
Georg Brandl116aa622007-08-15 14:28:22 +00001037
Georg Brandlbb27c122010-11-11 07:26:40 +00001038 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +00001039
Łukasz Langadaab1c82011-04-27 18:10:05 +02001040 Read and parse configuration data from *f* which must be an iterable
Łukasz Langaba702da2011-04-28 12:02:05 +02001041 yielding Unicode strings (for example files opened in text mode).
Georg Brandl116aa622007-08-15 14:28:22 +00001042
Georg Brandlbb27c122010-11-11 07:26:40 +00001043 Optional argument *source* specifies the name of the file being read. If
Fred Drake5a7c11f2010-11-13 05:24:17 +00001044 not given and *f* has a :attr:`name` attribute, that is used for
1045 *source*; the default is ``'<???>'``.
Fred Drakea4923622010-08-09 12:52:45 +00001046
Georg Brandlbb27c122010-11-11 07:26:40 +00001047 .. versionadded:: 3.2
Łukasz Langa43ae6192011-04-27 18:13:42 +02001048 Replaces :meth:`readfp`.
1049
Georg Brandlbb27c122010-11-11 07:26:40 +00001050 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +00001051
Fred Drake5a7c11f2010-11-13 05:24:17 +00001052 Parse configuration data from a string.
Fred Drakea4923622010-08-09 12:52:45 +00001053
Fred Drake5a7c11f2010-11-13 05:24:17 +00001054 Optional argument *source* specifies a context-specific name of the
1055 string passed. If not given, ``'<string>'`` is used. This should
1056 commonly be a filesystem path or a URL.
Fred Drakea4923622010-08-09 12:52:45 +00001057
Georg Brandlbb27c122010-11-11 07:26:40 +00001058 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001059
Fred Drakea4923622010-08-09 12:52:45 +00001060
Georg Brandlbb27c122010-11-11 07:26:40 +00001061 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +00001062
Łukasz Langa71b37a52010-12-17 21:56:32 +00001063 Load configuration from any object that provides a dict-like ``items()``
1064 method. Keys are section names, values are dictionaries with keys and
1065 values that should be present in the section. If the used dictionary
1066 type preserves order, sections and their keys will be added in order.
1067 Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +00001068
Georg Brandlbb27c122010-11-11 07:26:40 +00001069 Optional argument *source* specifies a context-specific name of the
1070 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001071
Łukasz Langa71b37a52010-12-17 21:56:32 +00001072 This method can be used to copy state between parsers.
1073
Georg Brandlbb27c122010-11-11 07:26:40 +00001074 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +00001075
Georg Brandl116aa622007-08-15 14:28:22 +00001076
Ezio Melottie927e252012-09-08 20:46:01 +03001077 .. method:: get(section, option, *, raw=False, vars=None[, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +00001078
Georg Brandlbb27c122010-11-11 07:26:40 +00001079 Get an *option* value for the named *section*. If *vars* is provided, it
1080 must be a dictionary. The *option* is looked up in *vars* (if provided),
1081 *section*, and in *DEFAULTSECT* in that order. If the key is not found
1082 and *fallback* is provided, it is used as a fallback value. ``None`` can
1083 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +00001084
Georg Brandlbb27c122010-11-11 07:26:40 +00001085 All the ``'%'`` interpolations are expanded in the return values, unless
1086 the *raw* argument is true. Values for interpolation keys are looked up
1087 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +00001088
Georg Brandlbb27c122010-11-11 07:26:40 +00001089 .. versionchanged:: 3.2
1090 Arguments *raw*, *vars* and *fallback* are keyword only to protect
1091 users from trying to use the third argument as the *fallback* fallback
1092 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +00001093
Łukasz Langa26d513c2010-11-10 18:57:39 +00001094
Ezio Melottie927e252012-09-08 20:46:01 +03001095 .. method:: getint(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001096
Georg Brandlbb27c122010-11-11 07:26:40 +00001097 A convenience method which coerces the *option* in the specified *section*
1098 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
1099 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001100
1101
Ezio Melottie927e252012-09-08 20:46:01 +03001102 .. method:: getfloat(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001103
Georg Brandlbb27c122010-11-11 07:26:40 +00001104 A convenience method which coerces the *option* in the specified *section*
1105 to a floating point number. See :meth:`get` for explanation of *raw*,
1106 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001107
1108
Ezio Melottie927e252012-09-08 20:46:01 +03001109 .. method:: getboolean(section, option, *, raw=False, vars=None[, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +00001110
Georg Brandlbb27c122010-11-11 07:26:40 +00001111 A convenience method which coerces the *option* in the specified *section*
1112 to a Boolean value. Note that the accepted values for the option are
Fred Drake5a7c11f2010-11-13 05:24:17 +00001113 ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
1114 return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
Georg Brandlbb27c122010-11-11 07:26:40 +00001115 cause it to return ``False``. These string values are checked in a
1116 case-insensitive manner. Any other value will cause it to raise
1117 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1118 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001119
1120
Ezio Melottie0add762012-09-14 06:32:35 +03001121 .. method:: items(raw=False, vars=None)
1122 items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001123
Łukasz Langa71b37a52010-12-17 21:56:32 +00001124 When *section* is not given, return a list of *section_name*,
1125 *section_proxy* pairs, including DEFAULTSECT.
1126
1127 Otherwise, return a list of *name*, *value* pairs for the options in the
1128 given *section*. Optional arguments have the same meaning as for the
Georg Brandlbb27c122010-11-11 07:26:40 +00001129 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001130
Georg Brandl116aa622007-08-15 14:28:22 +00001131
Georg Brandlbb27c122010-11-11 07:26:40 +00001132 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001133
Georg Brandlbb27c122010-11-11 07:26:40 +00001134 If the given section exists, set the given option to the specified value;
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001135 otherwise raise :exc:`NoSectionError`. *option* and *value* must be
1136 strings; if not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001137
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001138
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001139 .. method:: write(fileobject, space_around_delimiters=True)
1140
1141 Write a representation of the configuration to the specified :term:`file
1142 object`, which must be opened in text mode (accepting strings). This
1143 representation can be parsed by a future :meth:`read` call. If
1144 *space_around_delimiters* is true, delimiters between
1145 keys and values are surrounded by spaces.
1146
1147
1148 .. method:: remove_option(section, option)
1149
1150 Remove the specified *option* from the specified *section*. If the
1151 section does not exist, raise :exc:`NoSectionError`. If the option
1152 existed to be removed, return :const:`True`; otherwise return
1153 :const:`False`.
1154
1155
1156 .. method:: remove_section(section)
1157
1158 Remove the specified *section* from the configuration. If the section in
1159 fact existed, return ``True``. Otherwise return ``False``.
1160
1161
1162 .. method:: optionxform(option)
1163
1164 Transforms the option name *option* as found in an input file or as passed
1165 in by client code to the form that should be used in the internal
1166 structures. The default implementation returns a lower-case version of
1167 *option*; subclasses may override this or client code can set an attribute
1168 of this name on instances to affect this behavior.
1169
1170 You don't need to subclass the parser to use this method, you can also
1171 set it on an instance, to a function that takes a string argument and
1172 returns a string. Setting it to ``str``, for example, would make option
1173 names case sensitive::
1174
1175 cfgparser = ConfigParser()
1176 cfgparser.optionxform = str
1177
1178 Note that when reading configuration files, whitespace around the option
1179 names is stripped before :meth:`optionxform` is called.
1180
1181
1182 .. method:: readfp(fp, filename=None)
1183
1184 .. deprecated:: 3.2
1185 Use :meth:`read_file` instead.
1186
Łukasz Langaba702da2011-04-28 12:02:05 +02001187 .. versionchanged:: 3.2
Martin Panter1f106712017-01-29 23:33:27 +00001188 :meth:`readfp` now iterates on *fp* instead of calling ``fp.readline()``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001189
1190 For existing code calling :meth:`readfp` with arguments which don't
1191 support iteration, the following generator may be used as a wrapper
1192 around the file-like object::
1193
Martin Panter1f106712017-01-29 23:33:27 +00001194 def readline_generator(fp):
1195 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001196 while line:
1197 yield line
Martin Panter1f106712017-01-29 23:33:27 +00001198 line = fp.readline()
Łukasz Langaba702da2011-04-28 12:02:05 +02001199
Martin Panter1f106712017-01-29 23:33:27 +00001200 Instead of ``parser.readfp(fp)`` use
1201 ``parser.read_file(readline_generator(fp))``.
Łukasz Langaba702da2011-04-28 12:02:05 +02001202
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001203
1204.. data:: MAX_INTERPOLATION_DEPTH
1205
1206 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1207 parameter is false. This is relevant only when the default *interpolation*
1208 is used.
1209
1210
1211.. _rawconfigparser-objects:
1212
1213RawConfigParser Objects
1214-----------------------
1215
Miss Islington (bot)dc20d9d2018-06-08 12:26:07 -07001216.. class:: RawConfigParser(defaults=None, dict_type=dict, \
Ezio Melottie927e252012-09-08 20:46:01 +03001217 allow_no_value=False, *, delimiters=('=', ':'), \
1218 comment_prefixes=('#', ';'), \
1219 inline_comment_prefixes=None, strict=True, \
1220 empty_lines_in_values=True, \
1221 default_section=configparser.DEFAULTSECT[, \
1222 interpolation])
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001223
Łukasz Langaa5fab172017-08-24 09:43:53 -07001224 Legacy variant of the :class:`ConfigParser`. It has interpolation
1225 disabled by default and allows for non-string section names, option
1226 names, and values via its unsafe ``add_section`` and ``set`` methods,
1227 as well as the legacy ``defaults=`` keyword argument handling.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001228
Miss Islington (bot)dc20d9d2018-06-08 12:26:07 -07001229 .. versionchanged:: 3.7
1230 The default *dict_type* is :class:`dict`, since it now preserves
1231 insertion order.
1232
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001233 .. note::
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001234 Consider using :class:`ConfigParser` instead which checks types of
Łukasz Langa34cea142014-09-14 23:37:03 -07001235 the values to be stored internally. If you don't want interpolation, you
Łukasz Langa7f64c8a2010-12-16 01:16:22 +00001236 can use ``ConfigParser(interpolation=None)``.
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001237
1238
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001239 .. method:: add_section(section)
1240
1241 Add a section named *section* to the instance. If a section by the given
1242 name already exists, :exc:`DuplicateSectionError` is raised. If the
1243 *default section* name is passed, :exc:`ValueError` is raised.
1244
1245 Type of *section* is not checked which lets users create non-string named
Łukasz Langa34cea142014-09-14 23:37:03 -07001246 sections. This behaviour is unsupported and may cause internal errors.
Łukasz Langa2cf9ddb2010-12-04 12:46:01 +00001247
1248
Łukasz Langab6a6f5f2010-12-03 16:28:00 +00001249 .. method:: set(section, option, value)
1250
1251 If the given section exists, set the given option to the specified value;
1252 otherwise raise :exc:`NoSectionError`. While it is possible to use
1253 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
1254 set to true) for *internal* storage of non-string values, full
1255 functionality (including interpolation and output to files) can only be
1256 achieved using string values.
1257
1258 This method lets users assign non-string values to keys internally. This
1259 behaviour is unsupported and will cause errors when attempting to write
1260 to a file or get it in non-raw mode. **Use the mapping protocol API**
1261 which does not allow such assignments to take place.
1262
1263
Łukasz Langa26d513c2010-11-10 18:57:39 +00001264Exceptions
1265----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001266
Łukasz Langa26d513c2010-11-10 18:57:39 +00001267.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001268
Fred Drake5a7c11f2010-11-13 05:24:17 +00001269 Base class for all other :mod:`configparser` exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001270
Georg Brandl48310cd2009-01-03 21:18:54 +00001271
Łukasz Langa26d513c2010-11-10 18:57:39 +00001272.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001273
Łukasz Langa26d513c2010-11-10 18:57:39 +00001274 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001275
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001276
Łukasz Langa26d513c2010-11-10 18:57:39 +00001277.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001278
Łukasz Langa26d513c2010-11-10 18:57:39 +00001279 Exception raised if :meth:`add_section` is called with the name of a section
1280 that is already present or in strict parsers when a section if found more
1281 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001282
Łukasz Langa26d513c2010-11-10 18:57:39 +00001283 .. versionadded:: 3.2
1284 Optional ``source`` and ``lineno`` attributes and arguments to
1285 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001286
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001287
Łukasz Langa26d513c2010-11-10 18:57:39 +00001288.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001289
Łukasz Langa26d513c2010-11-10 18:57:39 +00001290 Exception raised by strict parsers if a single option appears twice during
1291 reading from a single file, string or dictionary. This catches misspellings
1292 and case sensitivity-related errors, e.g. a dictionary may have two keys
1293 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001294
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001295
Łukasz Langa26d513c2010-11-10 18:57:39 +00001296.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001297
Łukasz Langa26d513c2010-11-10 18:57:39 +00001298 Exception raised when a specified option is not found in the specified
1299 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001300
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001301
Łukasz Langa26d513c2010-11-10 18:57:39 +00001302.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001303
Łukasz Langa26d513c2010-11-10 18:57:39 +00001304 Base class for exceptions raised when problems occur performing string
1305 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001306
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001307
Łukasz Langa26d513c2010-11-10 18:57:39 +00001308.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001309
Łukasz Langa26d513c2010-11-10 18:57:39 +00001310 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001311 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001312 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001313
Fred Drake03c44a32010-02-19 06:08:41 +00001314
Łukasz Langa26d513c2010-11-10 18:57:39 +00001315.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001316
Georg Brandlbb27c122010-11-11 07:26:40 +00001317 Exception raised when an option referenced from a value does not exist.
1318 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001319
Fred Drake03c44a32010-02-19 06:08:41 +00001320
Łukasz Langa26d513c2010-11-10 18:57:39 +00001321.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001322
Georg Brandlbb27c122010-11-11 07:26:40 +00001323 Exception raised when the source text into which substitutions are made does
1324 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001325
Łukasz Langa26d513c2010-11-10 18:57:39 +00001326
1327.. exception:: MissingSectionHeaderError
1328
Georg Brandlbb27c122010-11-11 07:26:40 +00001329 Exception raised when attempting to parse a file which has no section
1330 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001331
1332
1333.. exception:: ParsingError
1334
1335 Exception raised when errors occur attempting to parse a file.
1336
1337 .. versionchanged:: 3.2
1338 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1339 ``source`` for consistency.
1340
Georg Brandlbb27c122010-11-11 07:26:40 +00001341
1342.. rubric:: Footnotes
1343
1344.. [1] Config parsers allow for heavy customization. If you are interested in
1345 changing the behaviour outlined by the footnote reference, consult the
1346 `Customizing Parser Behaviour`_ section.