blob: 2cef232bb5b40433e32db46098671db60c4e263f [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
18This module defines the class :class:`ConfigParser`. The :class:`ConfigParser`
19class implements a basic configuration file parser language which provides a
20structure similar to what you would find on Microsoft Windows INI files. You
21can use this to write Python programs which can be customized by end users
22easily.
23
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
Ezio Melotti832c8bb2011-04-14 06:41:38 +030029.. seealso::
30
31 Module :mod:`shlex`
32 Support for a creating Unix shell-like mini-languages which can be used
33 as an alternate format for application configuration files.
34
35 Module :mod:`json`
36 The json module implements a subset of JavaScript syntax which can also
37 be used for this purpose.
38
Georg Brandl116aa622007-08-15 14:28:22 +000039The configuration file consists of sections, led by a ``[section]`` header and
40followed by ``name: value`` entries, with continuations in the style of
Christian Heimesf6cd9672008-03-26 13:45:42 +000041:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
42accepted. Note that leading whitespace is removed from values. The optional
43values can contain format strings which refer to other values in the same
44section, or values in a special ``DEFAULT`` section. Additional defaults can be
45provided on initialization and retrieval. Lines beginning with ``'#'`` or
46``';'`` are ignored and may be used to provide comments.
Georg Brandl116aa622007-08-15 14:28:22 +000047
Georg Brandl1fa11af2010-08-01 21:03:01 +000048Configuration files may include comments, prefixed by specific characters (``#``
49and ``;``). Comments may appear on their own in an otherwise empty line, or may
Fred Drake8a7b89b2010-11-09 13:32:49 +000050be entered in lines holding values or section names. In the latter case, they
Georg Brandl1fa11af2010-08-01 21:03:01 +000051need to be preceded by a whitespace character to be recognized as a comment.
52(For backwards compatibility, only ``;`` starts an inline comment, while ``#``
53does not.)
54
55On top of the core functionality, :class:`SafeConfigParser` supports
56interpolation. This means values can contain format strings which refer to
57other values in the same section, or values in a special ``DEFAULT`` section.
58Additional defaults can be provided on initialization.
59
Georg Brandl116aa622007-08-15 14:28:22 +000060For example::
61
62 [My Section]
63 foodir: %(dir)s/whatever
64 dir=frob
Christian Heimesf6cd9672008-03-26 13:45:42 +000065 long: this value continues
66 in the next line
Georg Brandl116aa622007-08-15 14:28:22 +000067
68would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
69All reference expansions are done on demand.
70
71Default values can be specified by passing them into the :class:`ConfigParser`
72constructor as a dictionary. Additional defaults may be passed into the
73:meth:`get` method which will override all others.
74
Georg Brandlc5605df2009-08-13 08:26:44 +000075Sections are normally stored in a built-in dictionary. An alternative dictionary
Georg Brandl116aa622007-08-15 14:28:22 +000076type can be passed to the :class:`ConfigParser` constructor. For example, if a
77dictionary type is passed that sorts its keys, the sections will be sorted on
78write-back, as will be the keys within each section.
79
80
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000081.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 The basic configuration object. When *defaults* is given, it is initialized
84 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
85 be used to create the dictionary objects for the list of sections, for the
86 options within a section, and for the default values. This class does not
87 support the magical interpolation behavior.
88
Raymond Hettinger231b7f12009-03-03 00:23:19 +000089 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000090 The default *dict_type* is :class:`collections.OrderedDict`.
91
Georg Brandl116aa622007-08-15 14:28:22 +000092
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000093.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 Derived class of :class:`RawConfigParser` that implements the magical
96 interpolation feature and adds optional arguments to the :meth:`get` and
97 :meth:`items` methods. The values in *defaults* must be appropriate for the
98 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
99 its value is the section name, and will override any value provided in
100 *defaults*.
101
102 All option names used in interpolation will be passed through the
103 :meth:`optionxform` method just like any other option name reference. For
104 example, using the default implementation of :meth:`optionxform` (which converts
105 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
106 equivalent.
107
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000108 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000109 The default *dict_type* is :class:`collections.OrderedDict`.
110
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000112.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114 Derived class of :class:`ConfigParser` that implements a more-sane variant of
115 the magical interpolation feature. This implementation is more predictable as
116 well. New applications should prefer this version if they don't need to be
117 compatible with older versions of Python.
118
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000119 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl116aa622007-08-15 14:28:22 +0000120
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000121 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000122 The default *dict_type* is :class:`collections.OrderedDict`.
123
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Georg Brandl1fa11af2010-08-01 21:03:01 +0000125.. exception:: Error
126
127 Base class for all other configparser exceptions.
128
129
Georg Brandl116aa622007-08-15 14:28:22 +0000130.. exception:: NoSectionError
131
132 Exception raised when a specified section is not found.
133
134
135.. exception:: DuplicateSectionError
136
137 Exception raised if :meth:`add_section` is called with the name of a section
138 that is already present.
139
140
141.. exception:: NoOptionError
142
143 Exception raised when a specified option is not found in the specified section.
144
145
146.. exception:: InterpolationError
147
148 Base class for exceptions raised when problems occur performing string
149 interpolation.
150
151
152.. exception:: InterpolationDepthError
153
154 Exception raised when string interpolation cannot be completed because the
155 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
156 :exc:`InterpolationError`.
157
158
159.. exception:: InterpolationMissingOptionError
160
161 Exception raised when an option referenced from a value does not exist. Subclass
162 of :exc:`InterpolationError`.
163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. exception:: InterpolationSyntaxError
166
167 Exception raised when the source text into which substitutions are made does not
168 conform to the required syntax. Subclass of :exc:`InterpolationError`.
169
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171.. exception:: MissingSectionHeaderError
172
173 Exception raised when attempting to parse a file which has no section headers.
174
175
176.. exception:: ParsingError
177
178 Exception raised when errors occur attempting to parse a file.
179
180
181.. data:: MAX_INTERPOLATION_DEPTH
182
183 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
184 parameter is false. This is relevant only for the :class:`ConfigParser` class.
185
186
187.. seealso::
188
189 Module :mod:`shlex`
190 Support for a creating Unix shell-like mini-languages which can be used as an
191 alternate format for application configuration files.
192
193
194.. _rawconfigparser-objects:
195
196RawConfigParser Objects
197-----------------------
198
199:class:`RawConfigParser` instances have the following methods:
200
201
202.. method:: RawConfigParser.defaults()
203
204 Return a dictionary containing the instance-wide defaults.
205
206
207.. method:: RawConfigParser.sections()
208
209 Return a list of the sections available; ``DEFAULT`` is not included in the
210 list.
211
212
213.. method:: RawConfigParser.add_section(section)
214
215 Add a section named *section* to the instance. If a section by the given name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000216 already exists, :exc:`DuplicateSectionError` is raised. If the name
217 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
218 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220.. method:: RawConfigParser.has_section(section)
221
222 Indicates whether the named section is present in the configuration. The
223 ``DEFAULT`` section is not acknowledged.
224
225
226.. method:: RawConfigParser.options(section)
227
228 Returns a list of options available in the specified *section*.
229
230
231.. method:: RawConfigParser.has_option(section, option)
232
233 If the given section exists, and contains the given option, return
234 :const:`True`; otherwise return :const:`False`.
235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. method:: RawConfigParser.read(filenames)
238
239 Attempt to read and parse a list of filenames, returning a list of filenames
Georg Brandlf6945182008-02-01 11:56:49 +0000240 which were successfully parsed. If *filenames* is a string,
Georg Brandl116aa622007-08-15 14:28:22 +0000241 it is treated as a single filename. If a file named in *filenames* cannot be
242 opened, that file will be ignored. This is designed so that you can specify a
243 list of potential configuration file locations (for example, the current
244 directory, the user's home directory, and some system-wide directory), and all
245 existing configuration files in the list will be read. If none of the named
246 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
247 An application which requires initial values to be loaded from a file should
248 load the required file or files using :meth:`readfp` before calling :meth:`read`
249 for any optional files::
250
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000251 import configparser, os
Georg Brandl116aa622007-08-15 14:28:22 +0000252
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000253 config = configparser.ConfigParser()
Georg Brandl116aa622007-08-15 14:28:22 +0000254 config.readfp(open('defaults.cfg'))
255 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
256
Georg Brandl116aa622007-08-15 14:28:22 +0000257
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000258.. method:: RawConfigParser.readfp(fp, filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260 Read and parse configuration data from the file or file-like object in *fp*
Georg Brandl22fff432009-10-27 20:19:02 +0000261 (only the :meth:`readline` method is used). The file-like object must
262 operate in text mode, i.e. return strings from :meth:`readline`.
263
264 If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used
265 for *filename*; the default is ``<???>``.
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267
268.. method:: RawConfigParser.get(section, option)
269
270 Get an *option* value for the named *section*.
271
272
273.. method:: RawConfigParser.getint(section, option)
274
275 A convenience method which coerces the *option* in the specified *section* to an
276 integer.
277
278
279.. method:: RawConfigParser.getfloat(section, option)
280
281 A convenience method which coerces the *option* in the specified *section* to a
282 floating point number.
283
284
285.. method:: RawConfigParser.getboolean(section, option)
286
287 A convenience method which coerces the *option* in the specified *section* to a
288 Boolean value. Note that the accepted values for the option are ``"1"``,
289 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
290 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
291 ``False``. These string values are checked in a case-insensitive manner. Any
292 other value will cause it to raise :exc:`ValueError`.
293
294
295.. method:: RawConfigParser.items(section)
296
297 Return a list of ``(name, value)`` pairs for each option in the given *section*.
298
299
300.. method:: RawConfigParser.set(section, option, value)
301
302 If the given section exists, set the given option to the specified value;
303 otherwise raise :exc:`NoSectionError`. While it is possible to use
304 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
305 true) for *internal* storage of non-string values, full functionality (including
306 interpolation and output to files) can only be achieved using string values.
307
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309.. method:: RawConfigParser.write(fileobject)
310
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000311 Write a representation of the configuration to the specified :term:`file object`,
Georg Brandl22fff432009-10-27 20:19:02 +0000312 which must be opened in text mode (accepting strings). This representation
313 can be parsed by a future :meth:`read` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000314
Georg Brandl116aa622007-08-15 14:28:22 +0000315
316.. method:: RawConfigParser.remove_option(section, option)
317
318 Remove the specified *option* from the specified *section*. If the section does
319 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
320 return :const:`True`; otherwise return :const:`False`.
321
Georg Brandl116aa622007-08-15 14:28:22 +0000322
323.. method:: RawConfigParser.remove_section(section)
324
325 Remove the specified *section* from the configuration. If the section in fact
326 existed, return ``True``. Otherwise return ``False``.
327
328
329.. method:: RawConfigParser.optionxform(option)
330
Georg Brandl628e6f92009-10-27 20:24:45 +0000331 Transforms the option name *option* as found in an input file or as passed in
332 by client code to the form that should be used in the internal structures.
333 The default implementation returns a lower-case version of *option*;
334 subclasses may override this or client code can set an attribute of this name
335 on instances to affect this behavior.
336
337 You don't necessarily need to subclass a ConfigParser to use this method, you
338 can also re-set it on an instance, to a function that takes a string
339 argument. Setting it to ``str``, for example, would make option names case
340 sensitive::
341
342 cfgparser = ConfigParser()
343 ...
344 cfgparser.optionxform = str
345
346 Note that when reading configuration files, whitespace around the
347 option names are stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349
350.. _configparser-objects:
351
352ConfigParser Objects
353--------------------
354
355The :class:`ConfigParser` class extends some methods of the
356:class:`RawConfigParser` interface, adding some optional arguments.
357
358
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000359.. method:: ConfigParser.get(section, option, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Georg Brandl1fa11af2010-08-01 21:03:01 +0000361 Get an *option* value for the named *section*. If *vars* is provided, it
362 must be a dictionary. The *option* is looked up in *vars* (if provided),
363 *section*, and in *defaults* in that order.
364
365 All the ``'%'`` interpolations are expanded in the return values, unless the
366 *raw* argument is true. Values for interpolation keys are looked up in the
367 same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000370.. method:: ConfigParser.items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372 Return a list of ``(name, value)`` pairs for each option in the given *section*.
373 Optional arguments have the same meaning as for the :meth:`get` method.
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376.. _safeconfigparser-objects:
377
378SafeConfigParser Objects
379------------------------
380
381The :class:`SafeConfigParser` class implements the same extended interface as
382:class:`ConfigParser`, with the following addition:
383
384
385.. method:: SafeConfigParser.set(section, option, value)
386
387 If the given section exists, set the given option to the specified value;
Georg Brandlf6945182008-02-01 11:56:49 +0000388 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
389 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000391
392Examples
393--------
394
395An example of writing to a configuration file::
396
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000397 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000398
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000399 config = configparser.RawConfigParser()
Georg Brandl48310cd2009-01-03 21:18:54 +0000400
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000401 # When adding sections or items, add them in the reverse order of
402 # how you want them to be displayed in the actual file.
403 # In addition, please note that using RawConfigParser's and the raw
404 # mode of ConfigParser's respective set functions, you can assign
405 # non-string values to keys internally, but will receive an error
406 # when attempting to write to a file or when you get it in non-raw
407 # mode. SafeConfigParser does not allow such assignments to take place.
408 config.add_section('Section1')
409 config.set('Section1', 'int', '15')
410 config.set('Section1', 'bool', 'true')
411 config.set('Section1', 'float', '3.1415')
412 config.set('Section1', 'baz', 'fun')
413 config.set('Section1', 'bar', 'Python')
414 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl48310cd2009-01-03 21:18:54 +0000415
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000416 # Writing our configuration file to 'example.cfg'
Georg Brandl22fff432009-10-27 20:19:02 +0000417 with open('example.cfg', 'w') as configfile:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000418 config.write(configfile)
419
420An example of reading the configuration file again::
421
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000422 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000423
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000424 config = configparser.RawConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000425 config.read('example.cfg')
426
427 # getfloat() raises an exception if the value is not a float
428 # getint() and getboolean() also do this for their respective types
429 float = config.getfloat('Section1', 'float')
430 int = config.getint('Section1', 'int')
Georg Brandlf6945182008-02-01 11:56:49 +0000431 print(float + int)
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000432
433 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
434 # This is because we are using a RawConfigParser().
435 if config.getboolean('Section1', 'bool'):
Georg Brandlf6945182008-02-01 11:56:49 +0000436 print(config.get('Section1', 'foo'))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000437
438To get interpolation, you will need to use a :class:`ConfigParser` or
439:class:`SafeConfigParser`::
440
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000441 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000442
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000443 config = configparser.ConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000444 config.read('example.cfg')
445
446 # Set the third, optional argument of get to 1 if you wish to use raw mode.
Georg Brandlf6945182008-02-01 11:56:49 +0000447 print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
448 print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000449
450 # The optional fourth argument is a dict with members that will take
451 # precedence in interpolation.
Georg Brandlf6945182008-02-01 11:56:49 +0000452 print(config.get('Section1', 'foo', 0, {'bar': 'Documentation',
453 'baz': 'evil'}))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000454
Georg Brandl48310cd2009-01-03 21:18:54 +0000455Defaults are available in all three types of ConfigParsers. They are used in
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000456interpolation if an option used is not defined elsewhere. ::
457
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000458 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000459
460 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000461 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000462 config.read('example.cfg')
Georg Brandl48310cd2009-01-03 21:18:54 +0000463
Georg Brandlf6945182008-02-01 11:56:49 +0000464 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000465 config.remove_option('Section1', 'bar')
466 config.remove_option('Section1', 'baz')
Georg Brandlf6945182008-02-01 11:56:49 +0000467 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000468
469The function ``opt_move`` below can be used to move options between sections::
470
471 def opt_move(config, section1, section2, option):
472 try:
473 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000474 except configparser.NoSectionError:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000475 # Create non-existent section
476 config.add_section(section2)
477 opt_move(config, section1, section2, option)
Georg Brandl86def6c2008-01-21 20:36:10 +0000478 else:
479 config.remove_option(section1, option)