blob: 12a8f28aeb4b6f23bb6f06fcfb2e63190c136e04 [file] [log] [blame]
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00001:mod:`configparser` --- Configuration file parser
Georg Brandl116aa622007-08-15 14:28:22 +00002=================================================
3
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00004.. module:: configparser
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Configuration file parser.
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Ken Manheimer <klm@zope.com>
8.. moduleauthor:: Barry Warsaw <bwarsaw@python.org>
9.. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
Łukasz Langa26d513c2010-11-10 18:57:39 +000010.. moduleauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000011.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>
Łukasz Langa26d513c2010-11-10 18:57:39 +000012.. sectionauthor:: Łukasz Langa <lukasz@langa.pl>
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl116aa622007-08-15 14:28:22 +000014.. index::
15 pair: .ini; file
16 pair: configuration; file
17 single: ini file
18 single: Windows ini file
19
Georg Brandl96a60ae2010-07-28 13:13:46 +000020This module provides the classes :class:`RawConfigParser` and
21:class:`SafeConfigParser`. They implement a basic configuration file parser
22language which provides a structure similar to what you would find in Microsoft
23Windows INI files. You can use this to write Python programs which can be
24customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000025
Georg Brandle720c0a2009-04-27 16:20:50 +000026.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000027
Georg Brandle720c0a2009-04-27 16:20:50 +000028 This library does *not* interpret or write the value-type prefixes used in
29 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000030
Łukasz Langa26d513c2010-11-10 18:57:39 +000031.. seealso::
32
33 Module :mod:`shlex`
34 Support for a creating Unix shell-like mini-languages which can be used
35 as an alternate format for application configuration files.
36
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
58The supported file structure of INI files is described `in the following section
Georg Brandlbb27c122010-11-11 07:26:40 +000059<#supported-ini-file-structure>`_, fow now all there is to know is that 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
Georg Brandlbb27c122010-11-11 07:26:40 +000082As you can see, we can treat a config parser just like a dictionary. There are
Łukasz Langa26d513c2010-11-10 18:57:39 +000083a few differences, `outlined later on <#mapping-protocol-access>`_, but the
Georg Brandlbb27c122010-11-11 07:26:40 +000084behaviour is very close to what you would expect from a dictionary.
Łukasz Langa26d513c2010-11-10 18:57:39 +000085
Georg Brandlbb27c122010-11-11 07:26:40 +000086Now that we have created and saved a configuration file, let's try reading it
Łukasz Langa26d513c2010-11-10 18:57:39 +000087back and exploring the data it holds.
88
Ł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
Georg Brandlbb27c122010-11-11 07:26:40 +0000122As we can see above, the API is pretty straight forward. The only bit of magic
Łukasz Langa26d513c2010-11-10 18:57:39 +0000123involves the ``DEFAULT`` section which provides default values for all other
Georg Brandlbb27c122010-11-11 07:26:40 +0000124sections [1]_. Another thing to note is that keys in sections are
125case-insensitive so they're stored in lowercase [1]_.
126
Ł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
Georg Brandlbb27c122010-11-11 07:26:40 +0000142Converting to the boolean type is not that simple, though. Wrapping the return
Łukasz Langa26d513c2010-11-10 18:57:39 +0000143value around ``bool()`` would do us no good since ``bool('False')`` is still
Georg Brandlbb27c122010-11-11 07:26:40 +0000144``True``. This is why config parsers also provide :meth:`getboolean`. This
145handy method is also case insensitive and correctly recognizes boolean values
146from ``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [1]_. An
Łukasz Langa26d513c2010-11-10 18:57:39 +0000147example of getting the boolean value:
148
Ł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
Georg Brandlbb27c122010-11-11 07:26:40 +0000159:meth:`getint` and :meth:`getfloat` methods, but these are far less useful
Łukasz Langa26d513c2010-11-10 18:57:39 +0000160because explicit casting is enough for these types.
161
Georg Brandlbb27c122010-11-11 07:26:40 +0000162
Łukasz Langa26d513c2010-11-10 18:57:39 +0000163Fallback Values
164---------------
165
166As with a regular dictionary, you can use a section's :meth:`get` method to
167provide fallback values:
168
Łukasz Langa26d513c2010-11-10 18:57:39 +0000169.. doctest::
170
Georg Brandlbb27c122010-11-11 07:26:40 +0000171 >>> topsecret.get('Port')
172 '50022'
173 >>> topsecret.get('CompressionLevel')
174 '9'
175 >>> topsecret.get('Cipher')
176 >>> topsecret.get('Cipher', '3des-cbc')
177 '3des-cbc'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000178
Georg Brandlbb27c122010-11-11 07:26:40 +0000179Please note that default values have precedence over fallback values. For
Łukasz Langa26d513c2010-11-10 18:57:39 +0000180instance, in our example the ``CompressionLevel`` key was specified only in the
Georg Brandlbb27c122010-11-11 07:26:40 +0000181``DEFAULT`` section. If we try to get it from the section
182``topsecret.server.com``, we will always get the default, even if we specify a
183fallback:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000184
Łukasz Langa26d513c2010-11-10 18:57:39 +0000185.. doctest::
186
Georg Brandlbb27c122010-11-11 07:26:40 +0000187 >>> topsecret.get('CompressionLevel', '3')
188 '9'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000189
190One more thing to be aware of is that the parser-level :meth:`get` method
191provides a custom, more complex interface, maintained for backwards
Georg Brandlbb27c122010-11-11 07:26:40 +0000192compatibility. When using this method, a fallback value can be provided via the
Łukasz Langa26d513c2010-11-10 18:57:39 +0000193``fallback`` keyword-only argument:
194
Łukasz Langa26d513c2010-11-10 18:57:39 +0000195.. doctest::
196
Georg Brandlbb27c122010-11-11 07:26:40 +0000197 >>> config.get('bitbucket.org', 'monster',
198 ... fallback='No such things as monsters')
199 'No such things as monsters'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000200
201The same ``fallback`` argument can be used with the :meth:`getint`,
202:meth:`getfloat` and :meth:`getboolean` methods, for example:
203
Łukasz Langa26d513c2010-11-10 18:57:39 +0000204.. doctest::
205
Georg Brandlbb27c122010-11-11 07:26:40 +0000206 >>> 'BatchMode' in topsecret
207 False
208 >>> topsecret.getboolean('BatchMode', fallback=True)
209 True
210 >>> config['DEFAULT']['BatchMode'] = 'no'
211 >>> topsecret.getboolean('BatchMode', fallback=True)
212 False
213
Łukasz Langa26d513c2010-11-10 18:57:39 +0000214
215Supported INI File Structure
216----------------------------
217
Georg Brandl96a60ae2010-07-28 13:13:46 +0000218A configuration file consists of sections, each led by a ``[section]`` header,
Fred Drakea4923622010-08-09 12:52:45 +0000219followed by key/value entries separated by a specific string (``=`` or ``:`` by
Georg Brandlbb27c122010-11-11 07:26:40 +0000220default [1]_). By default, section names are case sensitive but keys are not
221[1]_. Leading und trailing whitespace is removed from keys and from values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000222Values can be omitted, in which case the key/value delimiter may also be left
223out. Values can also span multiple lines, as long as they are indented deeper
224than the first line of the value. Depending on the parser's mode, blank lines
225may be treated as parts of multiline values or ignored.
Georg Brandl96a60ae2010-07-28 13:13:46 +0000226
227Configuration files may include comments, prefixed by specific characters (``#``
Georg Brandlbb27c122010-11-11 07:26:40 +0000228and ``;`` by default [1]_). Comments may appear on their own in an otherwise
229empty line, or may be entered in lines holding values or section names. In the
230latter case, they need to be preceded by a whitespace character to be recognized
231as a comment. (For backwards compatibility, by default only ``;`` starts an
232inline comment, while ``#`` does not [1]_.)
Georg Brandl96a60ae2010-07-28 13:13:46 +0000233
234On top of the core functionality, :class:`SafeConfigParser` supports
235interpolation. This means values can contain format strings which refer to
Łukasz Langa26d513c2010-11-10 18:57:39 +0000236other values in the same section, or values in a special ``DEFAULT`` section
Georg Brandlbb27c122010-11-11 07:26:40 +0000237[1]_. Additional defaults can be provided on initialization.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000238
Georg Brandlbb27c122010-11-11 07:26:40 +0000239For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000240
Georg Brandlbb27c122010-11-11 07:26:40 +0000241.. code-block:: ini
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Georg Brandl96a60ae2010-07-28 13:13:46 +0000243 [Paths]
244 home_dir: /Users
245 my_dir: %(home_dir)s/lumberjack
246 my_pictures: %(my_dir)s/Pictures
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Georg Brandl96a60ae2010-07-28 13:13:46 +0000248 [Multiline Values]
249 chorus: I'm a lumberjack, and I'm okay
250 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +0000251
Georg Brandl96a60ae2010-07-28 13:13:46 +0000252 [No Values]
253 key_without_value
254 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +0000255
Georg Brandl96a60ae2010-07-28 13:13:46 +0000256 [You can use comments] ; after a useful line
257 ; in an empty line
258 after: a_value ; here's another comment
259 inside: a ;comment
260 multiline ;comment
261 value! ;comment
262
263 [Sections Can Be Indented]
264 can_values_be_as_well = True
265 does_that_mean_anything_special = False
266 purpose = formatting for readability
267 multiline_values = are
268 handled just fine as
269 long as they are indented
270 deeper than the first line
271 of a value
272 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +0000273
Georg Brandl96a60ae2010-07-28 13:13:46 +0000274In the example above, :class:`SafeConfigParser` would resolve ``%(home_dir)s``
275to the value of ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in
276effect would resolve to ``/Users/lumberjack``. All interpolations are done on
277demand so keys used in the chain of references do not have to be specified in
278any specific order in the configuration file.
279
280:class:`RawConfigParser` would simply return ``%(my_dir)s/Pictures`` as the
281value of ``my_pictures`` and ``%(home_dir)s/lumberjack`` as the value of
282``my_dir``. Other features presented in the example are handled in the same
283manner by both parsers.
284
Georg Brandlbb27c122010-11-11 07:26:40 +0000285
Łukasz Langa26d513c2010-11-10 18:57:39 +0000286Mapping Protocol Access
287-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000288
Łukasz Langa26d513c2010-11-10 18:57:39 +0000289.. versionadded:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000290
Łukasz Langa26d513c2010-11-10 18:57:39 +0000291Mapping protocol access is a generic name for functionality that enables using
Georg Brandlbb27c122010-11-11 07:26:40 +0000292custom objects as if they were dictionaries. In case of :mod:`configparser`,
Łukasz Langa26d513c2010-11-10 18:57:39 +0000293the mapping interface implementation is using the
294``parser['section']['option']`` notation.
295
296``parser['section']`` in particular returns a proxy for the section's data in
Georg Brandlbb27c122010-11-11 07:26:40 +0000297the parser. This means that the values are not copied but they are taken from
298the original parser on demand. What's even more important is that when values
Łukasz Langa26d513c2010-11-10 18:57:39 +0000299are changed on a section proxy, they are actually mutated in the original
300parser.
301
302:mod:`configparser` objects behave as close to actual dictionaries as possible.
303The mapping interface is complete and adheres to the ``MutableMapping`` ABC.
304However, there are a few differences that should be taken into account:
305
Georg Brandlbb27c122010-11-11 07:26:40 +0000306* By default, all keys in sections are accessible in a case-insensitive manner
307 [1]_. E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
308 option key names. This means lowercased keys by default. At the same time,
309 for a section that holds the key ``"a"``, both expressions return ``True``::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000310
Georg Brandlbb27c122010-11-11 07:26:40 +0000311 "a" in parser["section"]
312 "A" in parser["section"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000313
Georg Brandlbb27c122010-11-11 07:26:40 +0000314* All sections include ``DEFAULTSECT`` values as well which means that
315 ``.clear()`` on a section may not leave the section visibly empty. This is
Łukasz Langa26d513c2010-11-10 18:57:39 +0000316 because default values cannot be deleted from the section (because technically
Georg Brandlbb27c122010-11-11 07:26:40 +0000317 they are not there). If they are overriden in the section, deleting causes
318 the default value to be visible again. Trying to delete a default value
319 causes a ``KeyError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000320
Georg Brandlbb27c122010-11-11 07:26:40 +0000321* Trying to delete the ``DEFAULTSECT`` throws ``ValueError``.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000322
Georg Brandlbb27c122010-11-11 07:26:40 +0000323* There are two parser-level methods in the legacy API that hide the dictionary
324 interface and are incompatible:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000325
Georg Brandlbb27c122010-11-11 07:26:40 +0000326 * ``parser.get(section, option, **kwargs)`` - the second argument is **not** a
327 fallback value
Łukasz Langa26d513c2010-11-10 18:57:39 +0000328
Georg Brandlbb27c122010-11-11 07:26:40 +0000329 * ``parser.items(section)`` - this returns a list of ``(option, value)`` pairs
330 for a specified ``section``
Łukasz Langa26d513c2010-11-10 18:57:39 +0000331
332The mapping protocol is implemented on top of the existing legacy API so that
333subclassing the original interface makes the mappings work as expected as well.
Georg Brandlbb27c122010-11-11 07:26:40 +0000334One difference is the explicit lack of support for the ``__name__`` special key.
335This is because the existing behaviour of ``__name__`` is very inconsistent and
336supporting it would only lead to problems. Details `here
Łukasz Langa26d513c2010-11-10 18:57:39 +0000337<http://mail.python.org/pipermail/python-dev/2010-July/102556.html>`_.
338
Georg Brandlbb27c122010-11-11 07:26:40 +0000339
Łukasz Langa26d513c2010-11-10 18:57:39 +0000340Customizing Parser Behaviour
341----------------------------
342
343There are nearly as many INI format variants as there are applications using it.
344:mod:`configparser` goes a long way to provide support for the largest sensible
Georg Brandlbb27c122010-11-11 07:26:40 +0000345set of INI styles available. The default functionality is mainly dictated by
Łukasz Langa26d513c2010-11-10 18:57:39 +0000346historical background and it's very likely that you will want to customize some
347of the features.
348
349The most natural way to change the way a specific config parser works is to use
350the :meth:`__init__` options:
351
352* *defaults*, default value: ``None``
353
354 This option accepts a dictionary of key-value pairs which will be initially
Georg Brandlbb27c122010-11-11 07:26:40 +0000355 put in the ``DEFAULTSECT``. This makes for an elegant way to support concise
Łukasz Langa26d513c2010-11-10 18:57:39 +0000356 configuration files that don't specify values which are the same as the
357 documented default.
358
359 Hint: if you want to specify default values for a specific section, use the
360 :meth:`read_dict` before you read the actual file.
361
362* *dict_type*, default value: :class:`collections.OrderedDict`
363
364 This option has a major impact on how the mapping protocol will behave and how
Georg Brandlbb27c122010-11-11 07:26:40 +0000365 the written configuration files will look like. With the default ordered
Łukasz Langa26d513c2010-11-10 18:57:39 +0000366 dictionary, every section is stored in the order they were added to the
Georg Brandlbb27c122010-11-11 07:26:40 +0000367 parser. Same goes for options within sections.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000368
369 An alternative dictionary type can be used for example to sort sections and
Georg Brandlbb27c122010-11-11 07:26:40 +0000370 options on write-back. You can also use a regular dictionary for performance
Łukasz Langa26d513c2010-11-10 18:57:39 +0000371 reasons.
372
373 Please note: there are ways to add a set of key-value pairs in a single
Georg Brandlbb27c122010-11-11 07:26:40 +0000374 operation. When you use a regular dictionary in those operations, the order
375 of the keys may be random. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000376
Łukasz Langa26d513c2010-11-10 18:57:39 +0000377 .. doctest::
378
Georg Brandlbb27c122010-11-11 07:26:40 +0000379 >>> parser = configparser.RawConfigParser()
380 >>> parser.read_dict({'section1': {'key1': 'value1',
381 ... 'key2': 'value2',
382 ... 'key3': 'value3'},
383 ... 'section2': {'keyA': 'valueA',
384 ... 'keyB': 'valueB',
385 ... 'keyC': 'valueC'},
386 ... 'section3': {'foo': 'x',
387 ... 'bar': 'y',
388 ... 'baz': 'z'}
389 ... })
390 >>> parser.sections()
391 ['section3', 'section2', 'section1']
392 >>> [option for option in parser['section3']]
393 ['baz', 'foo', 'bar']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000394
395 In these operations you need to use an ordered dictionary as well:
396
Łukasz Langa26d513c2010-11-10 18:57:39 +0000397 .. doctest::
398
Georg Brandlbb27c122010-11-11 07:26:40 +0000399 >>> from collections import OrderedDict
400 >>> parser = configparser.RawConfigParser()
401 >>> parser.read_dict(
402 ... OrderedDict((
403 ... ('s1',
404 ... OrderedDict((
405 ... ('1', '2'),
406 ... ('3', '4'),
407 ... ('5', '6'),
408 ... ))
409 ... ),
410 ... ('s2',
411 ... OrderedDict((
412 ... ('a', 'b'),
413 ... ('c', 'd'),
414 ... ('e', 'f'),
415 ... ))
416 ... ),
417 ... ))
418 ... )
419 >>> parser.sections()
420 ['s1', 's2']
421 >>> [option for option in parser['s1']]
422 ['1', '3', '5']
423 >>> [option for option in parser['s2'].values()]
424 ['b', 'd', 'f']
Łukasz Langa26d513c2010-11-10 18:57:39 +0000425
426* *allow_no_value*, default value: ``False``
427
428 Some configuration files are known to include settings without values, but
429 which otherwise conform to the syntax supported by :mod:`configparser`. The
430 *allow_no_value* parameter to the :meth:`__init__` method can be used to
431 indicate that such values should be accepted:
432
Łukasz Langa26d513c2010-11-10 18:57:39 +0000433 .. doctest::
434
Georg Brandlbb27c122010-11-11 07:26:40 +0000435 >>> import configparser
Łukasz Langa26d513c2010-11-10 18:57:39 +0000436
Georg Brandlbb27c122010-11-11 07:26:40 +0000437 >>> sample_config = """
438 ... [mysqld]
439 ... user = mysql
440 ... pid-file = /var/run/mysqld/mysqld.pid
441 ... skip-external-locking
442 ... old_passwords = 1
443 ... skip-bdb
444 ... skip-innodb # we don't need ACID today
445 ... """
446 >>> config = configparser.RawConfigParser(allow_no_value=True)
447 >>> config.read_string(sample_config)
Łukasz Langa26d513c2010-11-10 18:57:39 +0000448
Georg Brandlbb27c122010-11-11 07:26:40 +0000449 >>> # Settings with values are treated as before:
450 >>> config["mysqld"]["user"]
451 'mysql'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000452
Georg Brandlbb27c122010-11-11 07:26:40 +0000453 >>> # Settings without values provide None:
454 >>> config["mysqld"]["skip-bdb"]
Łukasz Langa26d513c2010-11-10 18:57:39 +0000455
Georg Brandlbb27c122010-11-11 07:26:40 +0000456 >>> # Settings which aren't specified still raise an error:
457 >>> config["mysqld"]["does-not-exist"]
458 Traceback (most recent call last):
459 ...
460 KeyError: 'does-not-exist'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000461
462* *delimiters*, default value: ``('=', ':')``
463
464 Delimiters are substrings that delimit keys from values within a section. The
465 first occurence of a delimiting substring on a line is considered a delimiter.
466 This means values (but not keus) can contain substrings that are in the
467 *delimiters*.
468
469 See also the *space_around_delimiters* argument to
470 :meth:`RawConfigParser.write`.
471
472* *comment_prefixes*, default value: ``_COMPATIBLE`` (``'#'`` valid on empty
473 lines, ``';'`` valid also on non-empty lines)
474
475 Comment prefixes are substrings that indicate the start of a valid comment
Georg Brandlbb27c122010-11-11 07:26:40 +0000476 within a config file. The peculiar default value allows for comments starting
Łukasz Langa26d513c2010-11-10 18:57:39 +0000477 with ``'#'`` or ``';'`` but only the latter can be used in a non-empty line.
Georg Brandlbb27c122010-11-11 07:26:40 +0000478 This is obviously dictated by backwards compatibiliy. A more predictable
Łukasz Langa26d513c2010-11-10 18:57:39 +0000479 approach would be to specify prefixes as ``('#', ';')`` which will allow for
480 both prefixes to be used in non-empty lines.
481
482 Please note that config parsers don't support escaping of comment prefixes so
483 leaving characters out of *comment_prefixes* is a way of ensuring they can be
484 used as parts of keys or values.
485
486* *strict*, default value: ``False``
487
488 If set to ``True``, the parser will not allow for any section or option
489 duplicates while reading from a single source (using :meth:`read_file`,
Georg Brandlbb27c122010-11-11 07:26:40 +0000490 :meth:`read_string` or :meth:`read_dict`). The default is ``False`` only
491 because of backwards compatibility reasons. It is recommended to use strict
Łukasz Langa26d513c2010-11-10 18:57:39 +0000492 parsers in new applications.
493
494* *empty_lines_in_values*, default value: ``True``
495
Georg Brandlbb27c122010-11-11 07:26:40 +0000496 In config parsers, values can be multiline as long as they are indented deeper
497 than the key that holds them. By default parsers also let empty lines to be
498 parts of values. At the same time, keys can be arbitrarily indented
499 themselves to improve readability. In consequence, when configuration files
500 get big and complex, it is easy for the user to lose track of the file
501 structure. Take for instance:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000502
Georg Brandlbb27c122010-11-11 07:26:40 +0000503 .. code-block:: ini
Łukasz Langa26d513c2010-11-10 18:57:39 +0000504
Georg Brandlbb27c122010-11-11 07:26:40 +0000505 [Section]
506 key = multiline
507 value with a gotcha
Łukasz Langa26d513c2010-11-10 18:57:39 +0000508
Georg Brandlbb27c122010-11-11 07:26:40 +0000509 this = is still a part of the multiline value of 'key'
Łukasz Langa26d513c2010-11-10 18:57:39 +0000510
511
Georg Brandlbb27c122010-11-11 07:26:40 +0000512 This can be especially problematic for the user to see if she's using a
513 proportional font to edit the file. That is why when your application does
514 not need values with empty lines, you should consider disallowing them. This
515 will make empty lines split keys every time. In the example above, it would
Łukasz Langa26d513c2010-11-10 18:57:39 +0000516 produce two keys, ``key`` and ``this``.
517
Łukasz Langa26d513c2010-11-10 18:57:39 +0000518
519More advanced customization may be achieved by overriding default values of the
520following parser members:
521
522* `RawConfigParser.BOOLEAN_STATES`
523
524 By default when using :meth:`getboolean`, config parsers consider the
525 following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
Georg Brandlbb27c122010-11-11 07:26:40 +0000526 following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You
527 can override this by specifying a custom dictionary of strings and their
528 boolean outcomes. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000529
Łukasz Langa26d513c2010-11-10 18:57:39 +0000530 .. doctest::
531
Georg Brandlbb27c122010-11-11 07:26:40 +0000532 >>> custom = configparser.RawConfigParser()
533 >>> custom['section1'] = {'funky': 'nope'}
534 >>> custom['section1'].getboolean('funky')
535 Traceback (most recent call last):
536 ...
537 ValueError: Not a boolean: nope
538 >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
539 >>> custom['section1'].getboolean('funky')
540 False
Łukasz Langa26d513c2010-11-10 18:57:39 +0000541
542 Other typical boolean pairs include ``accept``/``reject`` or
543 ``enabled``/``disabled``.
544
545* :meth:`RawConfigParser.optionxform`
546
547 This is a method that transforms option names on every read or set operation.
Georg Brandlbb27c122010-11-11 07:26:40 +0000548 By default it converts the name to lowercase. This also means that when a
549 configuration file gets written, all keys will be lowercase. If you find that
550 behaviour unsuitable, you can override this method. For example:
Łukasz Langa26d513c2010-11-10 18:57:39 +0000551
Łukasz Langa26d513c2010-11-10 18:57:39 +0000552 .. doctest::
553
Georg Brandlbb27c122010-11-11 07:26:40 +0000554 >>> config = """
555 ... [Section1]
556 ... Key = Value
557 ...
558 ... [Section2]
559 ... AnotherKey = Value
560 ... """
561 >>> typical = configparser.RawConfigParser()
562 >>> typical.read_string(config)
563 >>> list(typical['Section1'].keys())
564 ['key']
565 >>> list(typical['Section2'].keys())
566 ['anotherkey']
567 >>> custom = configparser.RawConfigParser()
568 >>> custom.optionxform = lambda option: option
569 >>> custom.read_string(config)
570 >>> list(custom['Section1'].keys())
571 ['Key']
572 >>> list(custom['Section2'].keys())
573 ['AnotherKey']
574
Łukasz Langa26d513c2010-11-10 18:57:39 +0000575
576Legacy API Examples
577-------------------
578
Georg Brandlbb27c122010-11-11 07:26:40 +0000579Mainly because of backwards compatibility concerns, :mod:`configparser` provides
580also a legacy API with explicit ``get``/``set`` methods. While there are valid
581use cases for the methods outlined below, mapping protocol access is preferred
582for new projects. The legacy API is at times more advanced, low-level and
583downright counterintuitive.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000584
585An example of writing to a configuration file::
586
587 import configparser
588
589 config = configparser.RawConfigParser()
590
591 # Please note that using RawConfigParser's and the raw mode of
592 # ConfigParser's respective set functions, you can assign non-string values
593 # to keys internally, but will receive an error when attempting to write to
594 # a file or when you get it in non-raw mode. Setting values using the
595 # mapping protocol or SafeConfigParser's set() does not allow such
596 # assignments to take place.
597 config.add_section('Section1')
598 config.set('Section1', 'int', '15')
599 config.set('Section1', 'bool', 'true')
600 config.set('Section1', 'float', '3.1415')
601 config.set('Section1', 'baz', 'fun')
602 config.set('Section1', 'bar', 'Python')
603 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
604
605 # Writing our configuration file to 'example.cfg'
606 with open('example.cfg', 'w') as configfile:
607 config.write(configfile)
608
609An example of reading the configuration file again::
610
611 import configparser
612
613 config = configparser.RawConfigParser()
614 config.read('example.cfg')
615
616 # getfloat() raises an exception if the value is not a float
617 # getint() and getboolean() also do this for their respective types
618 float = config.getfloat('Section1', 'float')
619 int = config.getint('Section1', 'int')
620 print(float + int)
621
622 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
623 # This is because we are using a RawConfigParser().
624 if config.getboolean('Section1', 'bool'):
625 print(config.get('Section1', 'foo'))
626
627To get interpolation, you will need to use a :class:`SafeConfigParser` or, if
628you absolutely have to, a :class:`ConfigParser`::
629
630 import configparser
631
632 cfg = configparser.SafeConfigParser()
633 cfg.read('example.cfg')
634
635 # Set the optional `raw` argument of get() to True if you wish to disable
636 # interpolation in a single get operation.
637 print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
638 print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
639
640 # The optional `vars` argument is a dict with members that will take
641 # precedence in interpolation.
642 print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
643 'baz': 'evil'}))
644
645 # The optional `fallback` argument can be used to provide a fallback value
646 print(cfg.get('Section1', 'foo'))
647 # -> "Python is fun!"
648
649 print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
650 # -> "Python is fun!"
651
652 print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
653 # -> "No such things as monsters."
654
655 # A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
656 # but we can also use:
657
658 print(cfg.get('Section1', 'monster', fallback=None))
659 # -> None
660
661
Georg Brandlbb27c122010-11-11 07:26:40 +0000662Defaults are available in all three types of ConfigParsers. They are used in
Łukasz Langa26d513c2010-11-10 18:57:39 +0000663interpolation if an option used is not defined elsewhere. ::
664
665 import configparser
666
667 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
668 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
669 config.read('example.cfg')
670
671 print(config.get('Section1', 'foo')) # -> "Python is fun!"
672 config.remove_option('Section1', 'bar')
673 config.remove_option('Section1', 'baz')
674 print(config.get('Section1', 'foo')) # -> "Life is hard!"
675
Georg Brandlbb27c122010-11-11 07:26:40 +0000676
Łukasz Langa26d513c2010-11-10 18:57:39 +0000677.. _rawconfigparser-objects:
678
679RawConfigParser Objects
680-----------------------
Georg Brandl96a60ae2010-07-28 13:13:46 +0000681
Fred Drakea4923622010-08-09 12:52:45 +0000682.. 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 +0000683
684 The basic configuration object. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000685 into the dictionary of intrinsic defaults. When *dict_type* is given, it
686 will be used to create the dictionary objects for the list of sections, for
687 the options within a section, and for the default values.
688
689 When *delimiters* is given, it will be used as the set of substrings that
690 divide keys from values. When *comment_prefixes* is given, it will be used
691 as the set of substrings that prefix comments in a line, both for the whole
692 line and inline comments. For backwards compatibility, the default value for
693 *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can
694 start whole line comments while only ``;`` can start inline comments.
695
Fred Drakea4923622010-08-09 12:52:45 +0000696 When *strict* is ``True`` (default: ``False``), the parser won't allow for
697 any section or option duplicates while reading from a single source (file,
698 string or dictionary), raising :exc:`DuplicateSectionError` or
699 :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
700 (default: ``True``), each empty line marks the end of an option. Otherwise,
701 internal empty lines of a multiline option are kept as part of the value.
702 When *allow_no_value* is ``True`` (default: ``False``), options without
703 values are accepted; the value presented for these is ``None``.
Fred Drake03c44a32010-02-19 06:08:41 +0000704
Georg Brandl96a60ae2010-07-28 13:13:46 +0000705 This class does not support the magical interpolation behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000706
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000707 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000708 The default *dict_type* is :class:`collections.OrderedDict`.
709
Fred Drake03c44a32010-02-19 06:08:41 +0000710 .. versionchanged:: 3.2
Fred Drakea4923622010-08-09 12:52:45 +0000711 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
712 *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000713
Fred Drake03c44a32010-02-19 06:08:41 +0000714
Georg Brandlbb27c122010-11-11 07:26:40 +0000715 .. method:: defaults()
Georg Brandl116aa622007-08-15 14:28:22 +0000716
Georg Brandlbb27c122010-11-11 07:26:40 +0000717 Return a dictionary containing the instance-wide defaults.
Georg Brandl116aa622007-08-15 14:28:22 +0000718
719
Georg Brandlbb27c122010-11-11 07:26:40 +0000720 .. method:: sections()
Georg Brandl116aa622007-08-15 14:28:22 +0000721
Georg Brandlbb27c122010-11-11 07:26:40 +0000722 Return a list of the sections available; ``DEFAULT`` is not included in
723 the list.
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725
Georg Brandlbb27c122010-11-11 07:26:40 +0000726 .. method:: add_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000727
Georg Brandlbb27c122010-11-11 07:26:40 +0000728 Add a section named *section* to the instance. If a section by the given
729 name already exists, :exc:`DuplicateSectionError` is raised. If the name
730 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
731 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandlbb27c122010-11-11 07:26:40 +0000734 .. method:: has_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Georg Brandlbb27c122010-11-11 07:26:40 +0000736 Indicates whether the named section is present in the configuration. The
737 ``DEFAULT`` section is not acknowledged.
Georg Brandl116aa622007-08-15 14:28:22 +0000738
Georg Brandl116aa622007-08-15 14:28:22 +0000739
Georg Brandlbb27c122010-11-11 07:26:40 +0000740 .. method:: options(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000741
Georg Brandlbb27c122010-11-11 07:26:40 +0000742 Return a list of options available in the specified *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000743
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Georg Brandlbb27c122010-11-11 07:26:40 +0000745 .. method:: has_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000746
Georg Brandlbb27c122010-11-11 07:26:40 +0000747 If the given section exists, and contains the given option, return
748 :const:`True`; otherwise return :const:`False`.
Georg Brandl116aa622007-08-15 14:28:22 +0000749
Georg Brandl116aa622007-08-15 14:28:22 +0000750
Georg Brandlbb27c122010-11-11 07:26:40 +0000751 .. method:: read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Georg Brandlbb27c122010-11-11 07:26:40 +0000753 Attempt to read and parse a list of filenames, returning a list of
754 filenames which were successfully parsed. If *filenames* is a string, it
755 is treated as a single filename. If a file named in *filenames* cannot be
756 opened, that file will be ignored. This is designed so that you can
757 specify a list of potential configuration file locations (for example, the
758 current directory, the user's home directory, and some system-wide
759 directory), and all existing configuration files in the list will be read.
760 If none of the named files exist, the :class:`ConfigParser` instance will
761 contain an empty dataset. An application which requires initial values to
762 be loaded from a file should load the required file or files using
763 :meth:`read_file` before calling :meth:`read` for any optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000764
Georg Brandlbb27c122010-11-11 07:26:40 +0000765 import configparser, os
Georg Brandl8dcaa732010-07-29 12:17:40 +0000766
Georg Brandlbb27c122010-11-11 07:26:40 +0000767 config = configparser.ConfigParser()
768 config.read_file(open('defaults.cfg'))
769 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
770 encoding='cp1250')
Georg Brandl116aa622007-08-15 14:28:22 +0000771
Georg Brandlbb27c122010-11-11 07:26:40 +0000772 .. versionadded:: 3.2
773 The *encoding* parameter. Previously, all files were read using the
774 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000775
Georg Brandl116aa622007-08-15 14:28:22 +0000776
Georg Brandlbb27c122010-11-11 07:26:40 +0000777 .. method:: read_file(f, source=None)
Georg Brandl73753d32009-09-22 13:53:14 +0000778
Georg Brandlbb27c122010-11-11 07:26:40 +0000779 Read and parse configuration data from the file or file-like object in *f*
780 (only the :meth:`readline` method is used). The file-like object must
781 operate in text mode, i.e. return strings from :meth:`readline`.
Georg Brandl116aa622007-08-15 14:28:22 +0000782
Georg Brandlbb27c122010-11-11 07:26:40 +0000783 Optional argument *source* specifies the name of the file being read. If
784 not given and *f* has a :attr:`name` attribute, that is used for *source*;
785 the default is ``<???>``.
Fred Drakea4923622010-08-09 12:52:45 +0000786
Georg Brandlbb27c122010-11-11 07:26:40 +0000787 .. versionadded:: 3.2
788 Renamed from :meth:`readfp` (with the ``filename`` attribute renamed to
789 ``source`` for consistency with other ``read_*`` methods).
Fred Drakea4923622010-08-09 12:52:45 +0000790
Fred Drakea4923622010-08-09 12:52:45 +0000791
Georg Brandlbb27c122010-11-11 07:26:40 +0000792 .. method:: read_string(string, source='<string>')
Fred Drakea4923622010-08-09 12:52:45 +0000793
Georg Brandlbb27c122010-11-11 07:26:40 +0000794 Parse configuration data from a given string.
Fred Drakea4923622010-08-09 12:52:45 +0000795
Georg Brandlbb27c122010-11-11 07:26:40 +0000796 Optional argument *source* specifies a context-specific name of the string
797 passed. If not given, ``<string>`` is used.
Fred Drakea4923622010-08-09 12:52:45 +0000798
Georg Brandlbb27c122010-11-11 07:26:40 +0000799 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000800
Fred Drakea4923622010-08-09 12:52:45 +0000801
Georg Brandlbb27c122010-11-11 07:26:40 +0000802 .. method:: read_dict(dictionary, source='<dict>')
Fred Drakea4923622010-08-09 12:52:45 +0000803
Georg Brandlbb27c122010-11-11 07:26:40 +0000804 Load configuration from a dictionary. Keys are section names, values are
805 dictionaries with keys and values that should be present in the section.
806 If the used dictionary type preserves order, sections and their keys will
807 be added in order. Values are automatically converted to strings.
Fred Drakea4923622010-08-09 12:52:45 +0000808
Georg Brandlbb27c122010-11-11 07:26:40 +0000809 Optional argument *source* specifies a context-specific name of the
810 dictionary passed. If not given, ``<dict>`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000811
Georg Brandlbb27c122010-11-11 07:26:40 +0000812 .. versionadded:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000813
Georg Brandlbb27c122010-11-11 07:26:40 +0000814 .. method:: get(section, option, [vars, fallback])
815
816 Get an *option* value for the named *section*. If *vars* is provided, it
817 must be a dictionary. The *option* is looked up in *vars* (if provided),
818 *section*, and in *DEFAULTSECT* in that order. If the key is not found
819 and *fallback* is provided, it is used as a fallback value. ``None`` can
820 be provided as a *fallback* value.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000821
Georg Brandlbb27c122010-11-11 07:26:40 +0000822 .. versionchanged:: 3.2
823 Arguments *vars* and *fallback* are keyword only to protect users from
824 trying to use the third argument as the *fallback* fallback (especially
825 when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000826
827
Georg Brandlbb27c122010-11-11 07:26:40 +0000828 .. method:: getint(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000829
Georg Brandlbb27c122010-11-11 07:26:40 +0000830 A convenience method which coerces the *option* in the specified *section*
831 to an integer. See :meth:`get` for explanation of *vars* and *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833
Georg Brandlbb27c122010-11-11 07:26:40 +0000834 .. method:: getfloat(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000835
Georg Brandlbb27c122010-11-11 07:26:40 +0000836 A convenience method which coerces the *option* in the specified *section*
837 to a floating point number. See :meth:`get` for explanation of *vars* and
838 *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000839
840
Georg Brandlbb27c122010-11-11 07:26:40 +0000841 .. method:: getboolean(section, option, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000842
Georg Brandlbb27c122010-11-11 07:26:40 +0000843 A convenience method which coerces the *option* in the specified *section*
844 to a Boolean value. Note that the accepted values for the option are
845 ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
846 return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
847 cause it to return ``False``. These string values are checked in a
848 case-insensitive manner. Any other value will cause it to raise
849 :exc:`ValueError`. See :meth:`get` for explanation of *vars* and
850 *fallback*.
Georg Brandl116aa622007-08-15 14:28:22 +0000851
852
Georg Brandlbb27c122010-11-11 07:26:40 +0000853 .. method:: items(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000854
Georg Brandlbb27c122010-11-11 07:26:40 +0000855 Return a list of ``(name, value)`` pairs for each option in the given
856 *section*.
Georg Brandl116aa622007-08-15 14:28:22 +0000857
858
Georg Brandlbb27c122010-11-11 07:26:40 +0000859 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +0000860
Georg Brandlbb27c122010-11-11 07:26:40 +0000861 If the given section exists, set the given option to the specified value;
862 otherwise raise :exc:`NoSectionError`. While it is possible to use
863 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
864 set to true) for *internal* storage of non-string values, full
865 functionality (including interpolation and output to files) can only be
866 achieved using string values.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000867
Georg Brandlbb27c122010-11-11 07:26:40 +0000868 .. note::
Łukasz Langa26d513c2010-11-10 18:57:39 +0000869
Georg Brandlbb27c122010-11-11 07:26:40 +0000870 This method lets users assign non-string values to keys internally.
871 This behaviour is unsupported and will cause errors when attempting to
872 write to a file or get it in non-raw mode. **Use the mapping protocol
873 API** which does not allow such assignments to take place.
Georg Brandl116aa622007-08-15 14:28:22 +0000874
Georg Brandl116aa622007-08-15 14:28:22 +0000875
Georg Brandlbb27c122010-11-11 07:26:40 +0000876 .. method:: write(fileobject, space_around_delimiters=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000877
Georg Brandlbb27c122010-11-11 07:26:40 +0000878 Write a representation of the configuration to the specified :term:`file
879 object`, which must be opened in text mode (accepting strings). This
880 representation can be parsed by a future :meth:`read` call. If
881 ``space_around_delimiters`` is ``True`` (the default), delimiters between
882 keys and values are surrounded by spaces.
Georg Brandl116aa622007-08-15 14:28:22 +0000883
Georg Brandl116aa622007-08-15 14:28:22 +0000884
Georg Brandlbb27c122010-11-11 07:26:40 +0000885 .. method:: remove_option(section, option)
Georg Brandl116aa622007-08-15 14:28:22 +0000886
Georg Brandlbb27c122010-11-11 07:26:40 +0000887 Remove the specified *option* from the specified *section*. If the
888 section does not exist, raise :exc:`NoSectionError`. If the option
889 existed to be removed, return :const:`True`; otherwise return
890 :const:`False`.
Georg Brandl116aa622007-08-15 14:28:22 +0000891
Georg Brandl116aa622007-08-15 14:28:22 +0000892
Georg Brandlbb27c122010-11-11 07:26:40 +0000893 .. method:: remove_section(section)
Georg Brandl116aa622007-08-15 14:28:22 +0000894
Georg Brandlbb27c122010-11-11 07:26:40 +0000895 Remove the specified *section* from the configuration. If the section in
896 fact existed, return ``True``. Otherwise return ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +0000897
898
Georg Brandlbb27c122010-11-11 07:26:40 +0000899 .. method:: optionxform(option)
Georg Brandl116aa622007-08-15 14:28:22 +0000900
Georg Brandlbb27c122010-11-11 07:26:40 +0000901 Transforms the option name *option* as found in an input file or as passed
902 in by client code to the form that should be used in the internal
903 structures. The default implementation returns a lower-case version of
904 *option*; subclasses may override this or client code can set an attribute
905 of this name on instances to affect this behavior.
Georg Brandl495f7b52009-10-27 15:28:25 +0000906
Georg Brandlbb27c122010-11-11 07:26:40 +0000907 You don't necessarily need to subclass a ConfigParser to use this method,
908 you can also re-set it on an instance, to a function that takes a string
909 argument. Setting it to ``str``, for example, would make option names
910 case sensitive::
Georg Brandl495f7b52009-10-27 15:28:25 +0000911
Georg Brandlbb27c122010-11-11 07:26:40 +0000912 cfgparser = ConfigParser()
913 ...
914 cfgparser.optionxform = str
Georg Brandl495f7b52009-10-27 15:28:25 +0000915
Georg Brandlbb27c122010-11-11 07:26:40 +0000916 Note that when reading configuration files, whitespace around the option
917 names are stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000918
Georg Brandl67b21b72010-08-17 15:07:14 +0000919
Georg Brandlbb27c122010-11-11 07:26:40 +0000920 .. method:: readfp(fp, filename=None)
Fred Drakea4923622010-08-09 12:52:45 +0000921
Georg Brandlbb27c122010-11-11 07:26:40 +0000922 .. deprecated:: 3.2
923 Please use :meth:`read_file` instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000924
Georg Brandl67b21b72010-08-17 15:07:14 +0000925
Georg Brandl116aa622007-08-15 14:28:22 +0000926.. _configparser-objects:
927
928ConfigParser Objects
929--------------------
930
Łukasz Langa26d513c2010-11-10 18:57:39 +0000931.. warning::
Georg Brandlbb27c122010-11-11 07:26:40 +0000932 Whenever you can, consider using :class:`SafeConfigParser` which adds
933 validation and escaping for the interpolation.
Łukasz Langa26d513c2010-11-10 18:57:39 +0000934
Georg Brandl116aa622007-08-15 14:28:22 +0000935The :class:`ConfigParser` class extends some methods of the
Łukasz Langa26d513c2010-11-10 18:57:39 +0000936:class:`RawConfigParser` interface, adding some optional arguments.
937
938.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
939
940 Derived class of :class:`RawConfigParser` that implements the magical
941 interpolation feature and adds optional arguments to the :meth:`get` and
942 :meth:`items` methods.
943
944 :class:`SafeConfigParser` is generally recommended over this class if you
945 need interpolation.
946
947 The values in *defaults* must be appropriate for the ``%()s`` string
948 interpolation. Note that *__name__* is an intrinsic default; its value is
949 the section name, and will override any value provided in *defaults*.
950
951 All option names used in interpolation will be passed through the
952 :meth:`optionxform` method just like any other option name reference. For
953 example, using the default implementation of :meth:`optionxform` (which
954 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
955 %(BAR)s`` are equivalent.
956
957 .. versionchanged:: 3.1
958 The default *dict_type* is :class:`collections.OrderedDict`.
959
960 .. versionchanged:: 3.2
961 *allow_no_value*, *delimiters*, *comment_prefixes*,
962 *strict* and *empty_lines_in_values* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000963
964
Georg Brandlbb27c122010-11-11 07:26:40 +0000965 .. method:: get(section, option, raw=False, [vars, fallback])
Georg Brandl116aa622007-08-15 14:28:22 +0000966
Georg Brandlbb27c122010-11-11 07:26:40 +0000967 Get an *option* value for the named *section*. If *vars* is provided, it
968 must be a dictionary. The *option* is looked up in *vars* (if provided),
969 *section*, and in *DEFAULTSECT* in that order. If the key is not found
970 and *fallback* is provided, it is used as a fallback value. ``None`` can
971 be provided as a *fallback* value.
Georg Brandl470a1232010-07-29 14:17:12 +0000972
Georg Brandlbb27c122010-11-11 07:26:40 +0000973 All the ``'%'`` interpolations are expanded in the return values, unless
974 the *raw* argument is true. Values for interpolation keys are looked up
975 in the same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +0000976
Georg Brandlbb27c122010-11-11 07:26:40 +0000977 .. versionchanged:: 3.2
978 Arguments *raw*, *vars* and *fallback* are keyword only to protect
979 users from trying to use the third argument as the *fallback* fallback
980 (especially when using the mapping protocol).
Georg Brandl116aa622007-08-15 14:28:22 +0000981
Łukasz Langa26d513c2010-11-10 18:57:39 +0000982
Georg Brandlbb27c122010-11-11 07:26:40 +0000983 .. method:: getint(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000984
Georg Brandlbb27c122010-11-11 07:26:40 +0000985 A convenience method which coerces the *option* in the specified *section*
986 to an integer. See :meth:`get` for explanation of *raw*, *vars* and
987 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000988
989
Georg Brandlbb27c122010-11-11 07:26:40 +0000990 .. method:: getfloat(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000991
Georg Brandlbb27c122010-11-11 07:26:40 +0000992 A convenience method which coerces the *option* in the specified *section*
993 to a floating point number. See :meth:`get` for explanation of *raw*,
994 *vars* and *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +0000995
996
Georg Brandlbb27c122010-11-11 07:26:40 +0000997 .. method:: getboolean(section, option, raw=False, [vars, fallback])
Fred Drakecc645b92010-09-04 04:35:34 +0000998
Georg Brandlbb27c122010-11-11 07:26:40 +0000999 A convenience method which coerces the *option* in the specified *section*
1000 to a Boolean value. Note that the accepted values for the option are
1001 ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
1002 return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
1003 cause it to return ``False``. These string values are checked in a
1004 case-insensitive manner. Any other value will cause it to raise
1005 :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
1006 *fallback*.
Fred Drakecc645b92010-09-04 04:35:34 +00001007
1008
Georg Brandlbb27c122010-11-11 07:26:40 +00001009 .. method:: items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001010
Georg Brandlbb27c122010-11-11 07:26:40 +00001011 Return a list of ``(name, value)`` pairs for each option in the given
1012 *section*. Optional arguments have the same meaning as for the
1013 :meth:`get` method.
Georg Brandl116aa622007-08-15 14:28:22 +00001014
Georg Brandl116aa622007-08-15 14:28:22 +00001015
Łukasz Langa26d513c2010-11-10 18:57:39 +00001016.. data:: MAX_INTERPOLATION_DEPTH
1017
1018 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
1019 parameter is false. This is relevant only for the :class:`ConfigParser` class.
1020
Georg Brandlbb27c122010-11-11 07:26:40 +00001021
Georg Brandl116aa622007-08-15 14:28:22 +00001022.. _safeconfigparser-objects:
1023
1024SafeConfigParser Objects
1025------------------------
1026
Łukasz Langa26d513c2010-11-10 18:57:39 +00001027.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
1028
1029 Derived class of :class:`ConfigParser` that implements a sane variant of the
1030 magical interpolation feature. This implementation is more predictable as it
1031 validates the interpolation syntax used within a configuration file. This
1032 class also enables escaping the interpolation character (e.g. a key can have
1033 ``%`` as part of the value by specifying ``%%`` in the file).
1034
1035 Applications that don't require interpolation should use
1036 :class:`RawConfigParser`, otherwise :class:`SafeConfigParser` is the best
1037 option.
1038
1039 .. versionchanged:: 3.1
1040 The default *dict_type* is :class:`collections.OrderedDict`.
1041
1042 .. versionchanged:: 3.2
1043 *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
1044 *empty_lines_in_values* were added.
1045
1046
Georg Brandlbb27c122010-11-11 07:26:40 +00001047 The :class:`SafeConfigParser` class implements the same extended interface as
1048 :class:`ConfigParser`, with the following addition:
Georg Brandl116aa622007-08-15 14:28:22 +00001049
Georg Brandlbb27c122010-11-11 07:26:40 +00001050 .. method:: set(section, option, value)
Georg Brandl116aa622007-08-15 14:28:22 +00001051
Georg Brandlbb27c122010-11-11 07:26:40 +00001052 If the given section exists, set the given option to the specified value;
1053 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
1054 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +00001055
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001056
Łukasz Langa26d513c2010-11-10 18:57:39 +00001057Exceptions
1058----------
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001059
Łukasz Langa26d513c2010-11-10 18:57:39 +00001060.. exception:: Error
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001061
Łukasz Langa26d513c2010-11-10 18:57:39 +00001062 Base class for all other configparser exceptions.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001063
Georg Brandl48310cd2009-01-03 21:18:54 +00001064
Łukasz Langa26d513c2010-11-10 18:57:39 +00001065.. exception:: NoSectionError
Georg Brandl48310cd2009-01-03 21:18:54 +00001066
Łukasz Langa26d513c2010-11-10 18:57:39 +00001067 Exception raised when a specified section is not found.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001068
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001069
Łukasz Langa26d513c2010-11-10 18:57:39 +00001070.. exception:: DuplicateSectionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001071
Łukasz Langa26d513c2010-11-10 18:57:39 +00001072 Exception raised if :meth:`add_section` is called with the name of a section
1073 that is already present or in strict parsers when a section if found more
1074 than once in a single input file, string or dictionary.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001075
Łukasz Langa26d513c2010-11-10 18:57:39 +00001076 .. versionadded:: 3.2
1077 Optional ``source`` and ``lineno`` attributes and arguments to
1078 :meth:`__init__` were added.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001079
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001080
Łukasz Langa26d513c2010-11-10 18:57:39 +00001081.. exception:: DuplicateOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001082
Łukasz Langa26d513c2010-11-10 18:57:39 +00001083 Exception raised by strict parsers if a single option appears twice during
1084 reading from a single file, string or dictionary. This catches misspellings
1085 and case sensitivity-related errors, e.g. a dictionary may have two keys
1086 representing the same case-insensitive configuration key.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001087
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001088
Łukasz Langa26d513c2010-11-10 18:57:39 +00001089.. exception:: NoOptionError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001090
Łukasz Langa26d513c2010-11-10 18:57:39 +00001091 Exception raised when a specified option is not found in the specified
1092 section.
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001093
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001094
Łukasz Langa26d513c2010-11-10 18:57:39 +00001095.. exception:: InterpolationError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001096
Łukasz Langa26d513c2010-11-10 18:57:39 +00001097 Base class for exceptions raised when problems occur performing string
1098 interpolation.
Georg Brandl48310cd2009-01-03 21:18:54 +00001099
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001100
Łukasz Langa26d513c2010-11-10 18:57:39 +00001101.. exception:: InterpolationDepthError
Guido van Rossum2fd4f372007-11-29 18:43:05 +00001102
Łukasz Langa26d513c2010-11-10 18:57:39 +00001103 Exception raised when string interpolation cannot be completed because the
Georg Brandlbb27c122010-11-11 07:26:40 +00001104 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
Łukasz Langa26d513c2010-11-10 18:57:39 +00001105 :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001106
Fred Drake03c44a32010-02-19 06:08:41 +00001107
Łukasz Langa26d513c2010-11-10 18:57:39 +00001108.. exception:: InterpolationMissingOptionError
Fred Drake03c44a32010-02-19 06:08:41 +00001109
Georg Brandlbb27c122010-11-11 07:26:40 +00001110 Exception raised when an option referenced from a value does not exist.
1111 Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001112
Fred Drake03c44a32010-02-19 06:08:41 +00001113
Łukasz Langa26d513c2010-11-10 18:57:39 +00001114.. exception:: InterpolationSyntaxError
Fred Drake03c44a32010-02-19 06:08:41 +00001115
Georg Brandlbb27c122010-11-11 07:26:40 +00001116 Exception raised when the source text into which substitutions are made does
1117 not conform to the required syntax. Subclass of :exc:`InterpolationError`.
Fred Drake03c44a32010-02-19 06:08:41 +00001118
Łukasz Langa26d513c2010-11-10 18:57:39 +00001119
1120.. exception:: MissingSectionHeaderError
1121
Georg Brandlbb27c122010-11-11 07:26:40 +00001122 Exception raised when attempting to parse a file which has no section
1123 headers.
Łukasz Langa26d513c2010-11-10 18:57:39 +00001124
1125
1126.. exception:: ParsingError
1127
1128 Exception raised when errors occur attempting to parse a file.
1129
1130 .. versionchanged:: 3.2
1131 The ``filename`` attribute and :meth:`__init__` argument were renamed to
1132 ``source`` for consistency.
1133
Georg Brandlbb27c122010-11-11 07:26:40 +00001134
1135.. rubric:: Footnotes
1136
1137.. [1] Config parsers allow for heavy customization. If you are interested in
1138 changing the behaviour outlined by the footnote reference, consult the
1139 `Customizing Parser Behaviour`_ section.