blob: f77a5b806d6bb59723732a70fb69548772145766 [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>
10.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>
11
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index::
13 pair: .ini; file
14 pair: configuration; file
15 single: ini file
16 single: Windows ini file
17
Georg Brandl96a60ae2010-07-28 13:13:46 +000018This module provides the classes :class:`RawConfigParser` and
19:class:`SafeConfigParser`. They implement a basic configuration file parser
20language which provides a structure similar to what you would find in Microsoft
21Windows INI files. You can use this to write Python programs which can be
22customized by end users easily.
Georg Brandl116aa622007-08-15 14:28:22 +000023
Georg Brandle720c0a2009-04-27 16:20:50 +000024.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000025
Georg Brandle720c0a2009-04-27 16:20:50 +000026 This library does *not* interpret or write the value-type prefixes used in
27 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000028
Georg Brandl96a60ae2010-07-28 13:13:46 +000029A configuration file consists of sections, each led by a ``[section]`` header,
30followed by name/value entries separated by a specific string (``=`` or ``:`` by
31default). Note that leading whitespace is removed from values. Values can be
32ommitted, in which case the key/value delimiter may also be left out. Values
33can also span multiple lines, as long as they are indented deeper than the first
34line of the value. Depending on the parser's mode, blank lines may be treated
35as parts of multiline values or ignored.
36
37Configuration files may include comments, prefixed by specific characters (``#``
38and ``;`` by default). Comments may appear on their own in an otherwise empty
39line, or may be entered in lines holding values or spection names. In the
40latter case, they need to be preceded by a whitespace character to be recognized
41as a comment. (For backwards compatibility, by default only ``;`` starts an
42inline comment, while ``#`` does not.)
43
44On top of the core functionality, :class:`SafeConfigParser` supports
45interpolation. This means values can contain format strings which refer to
46other values in the same section, or values in a special ``DEFAULT`` section.
47Additional defaults can be provided on initialization and retrieval.
Georg Brandl116aa622007-08-15 14:28:22 +000048
49For example::
50
Georg Brandl96a60ae2010-07-28 13:13:46 +000051 [Paths]
52 home_dir: /Users
53 my_dir: %(home_dir)s/lumberjack
54 my_pictures: %(my_dir)s/Pictures
Georg Brandl116aa622007-08-15 14:28:22 +000055
Georg Brandl96a60ae2010-07-28 13:13:46 +000056 [Multiline Values]
57 chorus: I'm a lumberjack, and I'm okay
58 I sleep all night and I work all day
Georg Brandl116aa622007-08-15 14:28:22 +000059
Georg Brandl96a60ae2010-07-28 13:13:46 +000060 [No Values]
61 key_without_value
62 empty string value here =
Georg Brandl116aa622007-08-15 14:28:22 +000063
Georg Brandl96a60ae2010-07-28 13:13:46 +000064 [You can use comments] ; after a useful line
65 ; in an empty line
66 after: a_value ; here's another comment
67 inside: a ;comment
68 multiline ;comment
69 value! ;comment
70
71 [Sections Can Be Indented]
72 can_values_be_as_well = True
73 does_that_mean_anything_special = False
74 purpose = formatting for readability
75 multiline_values = are
76 handled just fine as
77 long as they are indented
78 deeper than the first line
79 of a value
80 # Did I mention we can indent comments, too?
Georg Brandl116aa622007-08-15 14:28:22 +000081
82
Georg Brandl96a60ae2010-07-28 13:13:46 +000083In the example above, :class:`SafeConfigParser` would resolve ``%(home_dir)s``
84to the value of ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in
85effect would resolve to ``/Users/lumberjack``. All interpolations are done on
86demand so keys used in the chain of references do not have to be specified in
87any specific order in the configuration file.
88
89:class:`RawConfigParser` would simply return ``%(my_dir)s/Pictures`` as the
90value of ``my_pictures`` and ``%(home_dir)s/lumberjack`` as the value of
91``my_dir``. Other features presented in the example are handled in the same
92manner by both parsers.
93
94Default values can be specified by passing them as a dictionary when
95constructing the :class:`SafeConfigParser`. Additional defaults may be passed
96to the :meth:`get` method which will override all others.
97
98Sections are normally stored in an :class:`collections.OrderedDict` which
99maintains the order of all keys. An alternative dictionary type can be passed
100to the :meth:`__init__` method. For example, if a dictionary type is passed
101that sorts its keys, the sections will be sorted on write-back, as will be the
102keys within each section.
103
104
105.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, empty_lines_in_values=True, allow_no_value=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107 The basic configuration object. When *defaults* is given, it is initialized
Georg Brandl96a60ae2010-07-28 13:13:46 +0000108 into the dictionary of intrinsic defaults. When *dict_type* is given, it
109 will be used to create the dictionary objects for the list of sections, for
110 the options within a section, and for the default values.
111
112 When *delimiters* is given, it will be used as the set of substrings that
113 divide keys from values. When *comment_prefixes* is given, it will be used
114 as the set of substrings that prefix comments in a line, both for the whole
115 line and inline comments. For backwards compatibility, the default value for
116 *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can
117 start whole line comments while only ``;`` can start inline comments.
118
119 When *empty_lines_in_values* is ``False`` (default: ``True``), each empty
120 line marks the end of an option. Otherwise, internal empty lines of a
121 multiline option are kept as part of the value. When *allow_no_value* is
122 true (default: ``False``), options without values are accepted; the value
Fred Drake03c44a32010-02-19 06:08:41 +0000123 presented for these is ``None``.
124
Georg Brandl96a60ae2010-07-28 13:13:46 +0000125 This class does not support the magical interpolation behavior.
Georg Brandl116aa622007-08-15 14:28:22 +0000126
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000127 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000128 The default *dict_type* is :class:`collections.OrderedDict`.
129
Fred Drake03c44a32010-02-19 06:08:41 +0000130 .. versionchanged:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000131 *delimiters*, *comment_prefixes*, *empty_lines_in_values* and
132 *allow_no_value* were added.
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Fred Drake03c44a32010-02-19 06:08:41 +0000134
Georg Brandl96a60ae2010-07-28 13:13:46 +0000135.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=('#', ';'), empty_lines_in_values=True, allow_no_value=False)
136
137 Derived class of :class:`ConfigParser` that implements a sane variant of the
138 magical interpolation feature. This implementation is more predictable as it
139 validates the interpolation syntax used within a configuration file. This
140 class also enables escaping the interpolation character (e.g. a key can have
141 ``%`` as part of the value by specifying ``%%`` in the file).
142
143 Applications that don't require interpolation should use
144 :class:`RawConfigParser`, otherwise :class:`SafeConfigParser` is the best
145 option.
146
147 .. versionchanged:: 3.1
148 The default *dict_type* is :class:`collections.OrderedDict`.
149
150 .. versionchanged:: 3.2
151 *delimiters*, *comment_prefixes*, *empty_lines_in_values* and
152 *allow_no_value* were added.
153
154
155.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=('#', ';'), empty_lines_in_values=True, allow_no_value=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157 Derived class of :class:`RawConfigParser` that implements the magical
158 interpolation feature and adds optional arguments to the :meth:`get` and
Georg Brandl96a60ae2010-07-28 13:13:46 +0000159 :meth:`items` methods.
160
161 :class:`SafeConfigParser` is generally recommended over this class if you
162 need interpolation.
163
164 The values in *defaults* must be appropriate for the ``%()s`` string
165 interpolation. Note that *__name__* is an intrinsic default; its value is
166 the section name, and will override any value provided in *defaults*.
Georg Brandl116aa622007-08-15 14:28:22 +0000167
168 All option names used in interpolation will be passed through the
169 :meth:`optionxform` method just like any other option name reference. For
Georg Brandl96a60ae2010-07-28 13:13:46 +0000170 example, using the default implementation of :meth:`optionxform` (which
171 converts option names to lower case), the values ``foo %(bar)s`` and ``foo
172 %(BAR)s`` are equivalent.
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000174 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000175 The default *dict_type* is :class:`collections.OrderedDict`.
176
Fred Drake03c44a32010-02-19 06:08:41 +0000177 .. versionchanged:: 3.2
Georg Brandl96a60ae2010-07-28 13:13:46 +0000178 *delimiters*, *comment_prefixes*, *empty_lines_in_values* and
179 *allow_no_value* were added.
Fred Drake03c44a32010-02-19 06:08:41 +0000180
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182.. exception:: NoSectionError
183
184 Exception raised when a specified section is not found.
185
186
187.. exception:: DuplicateSectionError
188
189 Exception raised if :meth:`add_section` is called with the name of a section
190 that is already present.
191
192
193.. exception:: NoOptionError
194
195 Exception raised when a specified option is not found in the specified section.
196
197
198.. exception:: InterpolationError
199
200 Base class for exceptions raised when problems occur performing string
201 interpolation.
202
203
204.. exception:: InterpolationDepthError
205
206 Exception raised when string interpolation cannot be completed because the
207 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
208 :exc:`InterpolationError`.
209
210
211.. exception:: InterpolationMissingOptionError
212
213 Exception raised when an option referenced from a value does not exist. Subclass
214 of :exc:`InterpolationError`.
215
Georg Brandl116aa622007-08-15 14:28:22 +0000216
217.. exception:: InterpolationSyntaxError
218
219 Exception raised when the source text into which substitutions are made does not
220 conform to the required syntax. Subclass of :exc:`InterpolationError`.
221
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. exception:: MissingSectionHeaderError
224
225 Exception raised when attempting to parse a file which has no section headers.
226
227
228.. exception:: ParsingError
229
230 Exception raised when errors occur attempting to parse a file.
231
232
233.. data:: MAX_INTERPOLATION_DEPTH
234
235 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
236 parameter is false. This is relevant only for the :class:`ConfigParser` class.
237
238
239.. seealso::
240
241 Module :mod:`shlex`
242 Support for a creating Unix shell-like mini-languages which can be used as an
243 alternate format for application configuration files.
244
245
246.. _rawconfigparser-objects:
247
248RawConfigParser Objects
249-----------------------
250
251:class:`RawConfigParser` instances have the following methods:
252
253
254.. method:: RawConfigParser.defaults()
255
256 Return a dictionary containing the instance-wide defaults.
257
258
259.. method:: RawConfigParser.sections()
260
261 Return a list of the sections available; ``DEFAULT`` is not included in the
262 list.
263
264
265.. method:: RawConfigParser.add_section(section)
266
267 Add a section named *section* to the instance. If a section by the given name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000268 already exists, :exc:`DuplicateSectionError` is raised. If the name
269 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
270 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272.. method:: RawConfigParser.has_section(section)
273
274 Indicates whether the named section is present in the configuration. The
275 ``DEFAULT`` section is not acknowledged.
276
277
278.. method:: RawConfigParser.options(section)
279
280 Returns a list of options available in the specified *section*.
281
282
283.. method:: RawConfigParser.has_option(section, option)
284
285 If the given section exists, and contains the given option, return
286 :const:`True`; otherwise return :const:`False`.
287
Georg Brandl116aa622007-08-15 14:28:22 +0000288
Georg Brandl8dcaa732010-07-29 12:17:40 +0000289.. method:: RawConfigParser.read(filenames, encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000290
291 Attempt to read and parse a list of filenames, returning a list of filenames
Georg Brandl8dcaa732010-07-29 12:17:40 +0000292 which were successfully parsed. If *filenames* is a string, it is treated as
293 a single filename. If a file named in *filenames* cannot be opened, that
294 file will be ignored. This is designed so that you can specify a list of
295 potential configuration file locations (for example, the current directory,
296 the user's home directory, and some system-wide directory), and all existing
297 configuration files in the list will be read. If none of the named files
298 exist, the :class:`ConfigParser` instance will contain an empty dataset. An
299 application which requires initial values to be loaded from a file should
300 load the required file or files using :meth:`readfp` before calling
301 :meth:`read` for any optional files::
Georg Brandl116aa622007-08-15 14:28:22 +0000302
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000303 import configparser, os
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000305 config = configparser.ConfigParser()
Georg Brandl116aa622007-08-15 14:28:22 +0000306 config.readfp(open('defaults.cfg'))
Georg Brandl8dcaa732010-07-29 12:17:40 +0000307 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250')
308
309 .. versionadded:: 3.2
310 The *encoding* parameter. Previously, all files were read using the
311 default encoding for :func:`open`.
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000314.. method:: RawConfigParser.readfp(fp, filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316 Read and parse configuration data from the file or file-like object in *fp*
Georg Brandl73753d32009-09-22 13:53:14 +0000317 (only the :meth:`readline` method is used). The file-like object must
318 operate in text mode, i.e. return strings from :meth:`readline`.
319
320 If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used
321 for *filename*; the default is ``<???>``.
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323
324.. method:: RawConfigParser.get(section, option)
325
326 Get an *option* value for the named *section*.
327
328
329.. method:: RawConfigParser.getint(section, option)
330
331 A convenience method which coerces the *option* in the specified *section* to an
332 integer.
333
334
335.. method:: RawConfigParser.getfloat(section, option)
336
337 A convenience method which coerces the *option* in the specified *section* to a
338 floating point number.
339
340
341.. method:: RawConfigParser.getboolean(section, option)
342
343 A convenience method which coerces the *option* in the specified *section* to a
344 Boolean value. Note that the accepted values for the option are ``"1"``,
345 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
346 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
347 ``False``. These string values are checked in a case-insensitive manner. Any
348 other value will cause it to raise :exc:`ValueError`.
349
350
351.. method:: RawConfigParser.items(section)
352
353 Return a list of ``(name, value)`` pairs for each option in the given *section*.
354
355
356.. method:: RawConfigParser.set(section, option, value)
357
358 If the given section exists, set the given option to the specified value;
359 otherwise raise :exc:`NoSectionError`. While it is possible to use
360 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
361 true) for *internal* storage of non-string values, full functionality (including
362 interpolation and output to files) can only be achieved using string values.
363
Georg Brandl116aa622007-08-15 14:28:22 +0000364
Georg Brandl96a60ae2010-07-28 13:13:46 +0000365.. method:: RawConfigParser.write(fileobject, space_around_delimiters=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Georg Brandl73753d32009-09-22 13:53:14 +0000367 Write a representation of the configuration to the specified file object,
368 which must be opened in text mode (accepting strings). This representation
Georg Brandl96a60ae2010-07-28 13:13:46 +0000369 can be parsed by a future :meth:`read` call. If ``space_around_delimiters``
370 is ``True`` (the default), delimiters between keys and values are surrounded
371 by spaces.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374.. method:: RawConfigParser.remove_option(section, option)
375
376 Remove the specified *option* from the specified *section*. If the section does
377 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
378 return :const:`True`; otherwise return :const:`False`.
379
Georg Brandl116aa622007-08-15 14:28:22 +0000380
381.. method:: RawConfigParser.remove_section(section)
382
383 Remove the specified *section* from the configuration. If the section in fact
384 existed, return ``True``. Otherwise return ``False``.
385
386
387.. method:: RawConfigParser.optionxform(option)
388
Georg Brandl495f7b52009-10-27 15:28:25 +0000389 Transforms the option name *option* as found in an input file or as passed in
390 by client code to the form that should be used in the internal structures.
391 The default implementation returns a lower-case version of *option*;
392 subclasses may override this or client code can set an attribute of this name
393 on instances to affect this behavior.
394
395 You don't necessarily need to subclass a ConfigParser to use this method, you
396 can also re-set it on an instance, to a function that takes a string
397 argument. Setting it to ``str``, for example, would make option names case
398 sensitive::
399
400 cfgparser = ConfigParser()
401 ...
402 cfgparser.optionxform = str
403
404 Note that when reading configuration files, whitespace around the
405 option names are stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407
408.. _configparser-objects:
409
410ConfigParser Objects
411--------------------
412
413The :class:`ConfigParser` class extends some methods of the
Georg Brandl96a60ae2010-07-28 13:13:46 +0000414:class:`RawConfigParser` interface, adding some optional arguments. Whenever you
415can, consider using :class:`SafeConfigParser` which adds validation and escaping
416for the interpolation.
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000419.. method:: ConfigParser.get(section, option, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Georg Brandl96a60ae2010-07-28 13:13:46 +0000421 Get an *option* value for the named *section*. All the ``'%'``
422 interpolations are expanded in the return values, based on the defaults
423 passed into the :meth:`__init__` method, as well as the options *vars*
424 provided, unless the *raw* argument is true.
Georg Brandl116aa622007-08-15 14:28:22 +0000425
426
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000427.. method:: ConfigParser.items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000428
Georg Brandl96a60ae2010-07-28 13:13:46 +0000429 Return a list of ``(name, value)`` pairs for each option in the given
430 *section*. Optional arguments have the same meaning as for the :meth:`get`
431 method.
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434.. _safeconfigparser-objects:
435
436SafeConfigParser Objects
437------------------------
438
439The :class:`SafeConfigParser` class implements the same extended interface as
440:class:`ConfigParser`, with the following addition:
441
442
443.. method:: SafeConfigParser.set(section, option, value)
444
445 If the given section exists, set the given option to the specified value;
Georg Brandlf6945182008-02-01 11:56:49 +0000446 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
447 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000449
450Examples
451--------
452
453An example of writing to a configuration file::
454
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000455 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000456
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000457 config = configparser.RawConfigParser()
Georg Brandl48310cd2009-01-03 21:18:54 +0000458
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000459 # When adding sections or items, add them in the reverse order of
460 # how you want them to be displayed in the actual file.
461 # In addition, please note that using RawConfigParser's and the raw
462 # mode of ConfigParser's respective set functions, you can assign
463 # non-string values to keys internally, but will receive an error
464 # when attempting to write to a file or when you get it in non-raw
465 # mode. SafeConfigParser does not allow such assignments to take place.
466 config.add_section('Section1')
467 config.set('Section1', 'int', '15')
468 config.set('Section1', 'bool', 'true')
469 config.set('Section1', 'float', '3.1415')
470 config.set('Section1', 'baz', 'fun')
471 config.set('Section1', 'bar', 'Python')
472 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl48310cd2009-01-03 21:18:54 +0000473
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000474 # Writing our configuration file to 'example.cfg'
Georg Brandl73753d32009-09-22 13:53:14 +0000475 with open('example.cfg', 'w') as configfile:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000476 config.write(configfile)
477
478An example of reading the configuration file again::
479
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000480 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000481
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000482 config = configparser.RawConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000483 config.read('example.cfg')
484
485 # getfloat() raises an exception if the value is not a float
486 # getint() and getboolean() also do this for their respective types
487 float = config.getfloat('Section1', 'float')
488 int = config.getint('Section1', 'int')
Georg Brandlf6945182008-02-01 11:56:49 +0000489 print(float + int)
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000490
491 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
492 # This is because we are using a RawConfigParser().
493 if config.getboolean('Section1', 'bool'):
Georg Brandlf6945182008-02-01 11:56:49 +0000494 print(config.get('Section1', 'foo'))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000495
496To get interpolation, you will need to use a :class:`ConfigParser` or
497:class:`SafeConfigParser`::
498
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000499 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000500
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000501 config = configparser.ConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000502 config.read('example.cfg')
503
504 # Set the third, optional argument of get to 1 if you wish to use raw mode.
Georg Brandlf6945182008-02-01 11:56:49 +0000505 print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
506 print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000507
508 # The optional fourth argument is a dict with members that will take
509 # precedence in interpolation.
Georg Brandlf6945182008-02-01 11:56:49 +0000510 print(config.get('Section1', 'foo', 0, {'bar': 'Documentation',
511 'baz': 'evil'}))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000512
Georg Brandl48310cd2009-01-03 21:18:54 +0000513Defaults are available in all three types of ConfigParsers. They are used in
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000514interpolation if an option used is not defined elsewhere. ::
515
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000516 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000517
518 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000519 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000520 config.read('example.cfg')
Georg Brandl48310cd2009-01-03 21:18:54 +0000521
Georg Brandlf6945182008-02-01 11:56:49 +0000522 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000523 config.remove_option('Section1', 'bar')
524 config.remove_option('Section1', 'baz')
Georg Brandlf6945182008-02-01 11:56:49 +0000525 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000526
527The function ``opt_move`` below can be used to move options between sections::
528
529 def opt_move(config, section1, section2, option):
530 try:
531 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000532 except configparser.NoSectionError:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000533 # Create non-existent section
534 config.add_section(section2)
535 opt_move(config, section1, section2, option)
Georg Brandl86def6c2008-01-21 20:36:10 +0000536 else:
537 config.remove_option(section1, option)
Fred Drake03c44a32010-02-19 06:08:41 +0000538
539Some configuration files are known to include settings without values, but which
540otherwise conform to the syntax supported by :mod:`configparser`. The
Georg Brandl96a60ae2010-07-28 13:13:46 +0000541*allow_no_value* parameter to the :meth:`__init__` method can be used to
542indicate that such values should be accepted:
Fred Drake03c44a32010-02-19 06:08:41 +0000543
544.. doctest::
545
546 >>> import configparser
547 >>> import io
548
549 >>> sample_config = """
550 ... [mysqld]
Georg Brandl96a60ae2010-07-28 13:13:46 +0000551 ... user = mysql
552 ... pid-file = /var/run/mysqld/mysqld.pid
553 ... skip-external-locking
554 ... old_passwords = 1
555 ... skip-bdb
556 ... skip-innodb # we don't need ACID today
Fred Drake03c44a32010-02-19 06:08:41 +0000557 ... """
558 >>> config = configparser.RawConfigParser(allow_no_value=True)
559 >>> config.readfp(io.BytesIO(sample_config))
560
561 >>> # Settings with values are treated as before:
562 >>> config.get("mysqld", "user")
563 'mysql'
564
565 >>> # Settings without values provide None:
566 >>> config.get("mysqld", "skip-bdb")
567
568 >>> # Settings which aren't specified still raise an error:
569 >>> config.get("mysqld", "does-not-exist")
570 Traceback (most recent call last):
571 ...
572 configparser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'