blob: 34a40ee79fc07af236273e23fdb44da8d10d4297 [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
29The configuration file consists of sections, led by a ``[section]`` header and
30followed by ``name: value`` entries, with continuations in the style of
Christian Heimesf6cd9672008-03-26 13:45:42 +000031:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
32accepted. Note that leading whitespace is removed from values. The optional
33values can contain format strings which refer to other values in the same
34section, or values in a special ``DEFAULT`` section. Additional defaults can be
35provided on initialization and retrieval. Lines beginning with ``'#'`` or
36``';'`` are ignored and may be used to provide comments.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38For example::
39
40 [My Section]
41 foodir: %(dir)s/whatever
42 dir=frob
Christian Heimesf6cd9672008-03-26 13:45:42 +000043 long: this value continues
44 in the next line
Georg Brandl116aa622007-08-15 14:28:22 +000045
46would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
47All reference expansions are done on demand.
48
49Default values can be specified by passing them into the :class:`ConfigParser`
50constructor as a dictionary. Additional defaults may be passed into the
51:meth:`get` method which will override all others.
52
Georg Brandl22b34312009-07-26 14:54:51 +000053Sections are normally stored in a built-in dictionary. An alternative dictionary
Georg Brandl116aa622007-08-15 14:28:22 +000054type can be passed to the :class:`ConfigParser` constructor. For example, if a
55dictionary type is passed that sorts its keys, the sections will be sorted on
56write-back, as will be the keys within each section.
57
58
Fred Drake03c44a32010-02-19 06:08:41 +000059.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict,
60 allow_no_value=False)
Georg Brandl116aa622007-08-15 14:28:22 +000061
62 The basic configuration object. When *defaults* is given, it is initialized
63 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
64 be used to create the dictionary objects for the list of sections, for the
Fred Drake03c44a32010-02-19 06:08:41 +000065 options within a section, and for the default values. When *allow_no_value*
66 is true (default: ``False``), options without values are accepted; the value
67 presented for these is ``None``.
68
69 This class does not
Georg Brandl116aa622007-08-15 14:28:22 +000070 support the magical interpolation behavior.
71
Raymond Hettinger231b7f12009-03-03 00:23:19 +000072 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000073 The default *dict_type* is :class:`collections.OrderedDict`.
74
Fred Drake03c44a32010-02-19 06:08:41 +000075 .. versionchanged:: 3.2
76 *allow_no_value* was added.
Georg Brandl116aa622007-08-15 14:28:22 +000077
Fred Drake03c44a32010-02-19 06:08:41 +000078
79.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict,
80 allow_no_value=False)
Georg Brandl116aa622007-08-15 14:28:22 +000081
82 Derived class of :class:`RawConfigParser` that implements the magical
83 interpolation feature and adds optional arguments to the :meth:`get` and
84 :meth:`items` methods. The values in *defaults* must be appropriate for the
85 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
86 its value is the section name, and will override any value provided in
87 *defaults*.
88
89 All option names used in interpolation will be passed through the
90 :meth:`optionxform` method just like any other option name reference. For
91 example, using the default implementation of :meth:`optionxform` (which converts
92 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
93 equivalent.
94
Raymond Hettinger231b7f12009-03-03 00:23:19 +000095 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000096 The default *dict_type* is :class:`collections.OrderedDict`.
97
Fred Drake03c44a32010-02-19 06:08:41 +000098 .. versionchanged:: 3.2
99 *allow_no_value* was added.
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Fred Drake03c44a32010-02-19 06:08:41 +0000101
102.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict,
103 allow_no_value=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000104
105 Derived class of :class:`ConfigParser` that implements a more-sane variant of
106 the magical interpolation feature. This implementation is more predictable as
107 well. New applications should prefer this version if they don't need to be
108 compatible with older versions of Python.
109
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000110 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl116aa622007-08-15 14:28:22 +0000111
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000112 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000113 The default *dict_type* is :class:`collections.OrderedDict`.
114
Fred Drake03c44a32010-02-19 06:08:41 +0000115 .. versionchanged:: 3.2
116 *allow_no_value* was added.
117
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119.. exception:: NoSectionError
120
121 Exception raised when a specified section is not found.
122
123
124.. exception:: DuplicateSectionError
125
126 Exception raised if :meth:`add_section` is called with the name of a section
127 that is already present.
128
129
130.. exception:: NoOptionError
131
132 Exception raised when a specified option is not found in the specified section.
133
134
135.. exception:: InterpolationError
136
137 Base class for exceptions raised when problems occur performing string
138 interpolation.
139
140
141.. exception:: InterpolationDepthError
142
143 Exception raised when string interpolation cannot be completed because the
144 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
145 :exc:`InterpolationError`.
146
147
148.. exception:: InterpolationMissingOptionError
149
150 Exception raised when an option referenced from a value does not exist. Subclass
151 of :exc:`InterpolationError`.
152
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154.. exception:: InterpolationSyntaxError
155
156 Exception raised when the source text into which substitutions are made does not
157 conform to the required syntax. Subclass of :exc:`InterpolationError`.
158
Georg Brandl116aa622007-08-15 14:28:22 +0000159
160.. exception:: MissingSectionHeaderError
161
162 Exception raised when attempting to parse a file which has no section headers.
163
164
165.. exception:: ParsingError
166
167 Exception raised when errors occur attempting to parse a file.
168
169
170.. data:: MAX_INTERPOLATION_DEPTH
171
172 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
173 parameter is false. This is relevant only for the :class:`ConfigParser` class.
174
175
176.. seealso::
177
178 Module :mod:`shlex`
179 Support for a creating Unix shell-like mini-languages which can be used as an
180 alternate format for application configuration files.
181
182
183.. _rawconfigparser-objects:
184
185RawConfigParser Objects
186-----------------------
187
188:class:`RawConfigParser` instances have the following methods:
189
190
191.. method:: RawConfigParser.defaults()
192
193 Return a dictionary containing the instance-wide defaults.
194
195
196.. method:: RawConfigParser.sections()
197
198 Return a list of the sections available; ``DEFAULT`` is not included in the
199 list.
200
201
202.. method:: RawConfigParser.add_section(section)
203
204 Add a section named *section* to the instance. If a section by the given name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000205 already exists, :exc:`DuplicateSectionError` is raised. If the name
206 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
207 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209.. method:: RawConfigParser.has_section(section)
210
211 Indicates whether the named section is present in the configuration. The
212 ``DEFAULT`` section is not acknowledged.
213
214
215.. method:: RawConfigParser.options(section)
216
217 Returns a list of options available in the specified *section*.
218
219
220.. method:: RawConfigParser.has_option(section, option)
221
222 If the given section exists, and contains the given option, return
223 :const:`True`; otherwise return :const:`False`.
224
Georg Brandl116aa622007-08-15 14:28:22 +0000225
226.. method:: RawConfigParser.read(filenames)
227
228 Attempt to read and parse a list of filenames, returning a list of filenames
Georg Brandlf6945182008-02-01 11:56:49 +0000229 which were successfully parsed. If *filenames* is a string,
Georg Brandl116aa622007-08-15 14:28:22 +0000230 it is treated as a single filename. If a file named in *filenames* cannot be
231 opened, that file will be ignored. This is designed so that you can specify a
232 list of potential configuration file locations (for example, the current
233 directory, the user's home directory, and some system-wide directory), and all
234 existing configuration files in the list will be read. If none of the named
235 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
236 An application which requires initial values to be loaded from a file should
237 load the required file or files using :meth:`readfp` before calling :meth:`read`
238 for any optional files::
239
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000240 import configparser, os
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000242 config = configparser.ConfigParser()
Georg Brandl116aa622007-08-15 14:28:22 +0000243 config.readfp(open('defaults.cfg'))
244 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
245
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000247.. method:: RawConfigParser.readfp(fp, filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000248
249 Read and parse configuration data from the file or file-like object in *fp*
Georg Brandl73753d32009-09-22 13:53:14 +0000250 (only the :meth:`readline` method is used). The file-like object must
251 operate in text mode, i.e. return strings from :meth:`readline`.
252
253 If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used
254 for *filename*; the default is ``<???>``.
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256
257.. method:: RawConfigParser.get(section, option)
258
259 Get an *option* value for the named *section*.
260
261
262.. method:: RawConfigParser.getint(section, option)
263
264 A convenience method which coerces the *option* in the specified *section* to an
265 integer.
266
267
268.. method:: RawConfigParser.getfloat(section, option)
269
270 A convenience method which coerces the *option* in the specified *section* to a
271 floating point number.
272
273
274.. method:: RawConfigParser.getboolean(section, option)
275
276 A convenience method which coerces the *option* in the specified *section* to a
277 Boolean value. Note that the accepted values for the option are ``"1"``,
278 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
279 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
280 ``False``. These string values are checked in a case-insensitive manner. Any
281 other value will cause it to raise :exc:`ValueError`.
282
283
284.. method:: RawConfigParser.items(section)
285
286 Return a list of ``(name, value)`` pairs for each option in the given *section*.
287
288
289.. method:: RawConfigParser.set(section, option, value)
290
291 If the given section exists, set the given option to the specified value;
292 otherwise raise :exc:`NoSectionError`. While it is possible to use
293 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
294 true) for *internal* storage of non-string values, full functionality (including
295 interpolation and output to files) can only be achieved using string values.
296
Georg Brandl116aa622007-08-15 14:28:22 +0000297
298.. method:: RawConfigParser.write(fileobject)
299
Georg Brandl73753d32009-09-22 13:53:14 +0000300 Write a representation of the configuration to the specified file object,
301 which must be opened in text mode (accepting strings). This representation
302 can be parsed by a future :meth:`read` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305.. method:: RawConfigParser.remove_option(section, option)
306
307 Remove the specified *option* from the specified *section*. If the section does
308 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
309 return :const:`True`; otherwise return :const:`False`.
310
Georg Brandl116aa622007-08-15 14:28:22 +0000311
312.. method:: RawConfigParser.remove_section(section)
313
314 Remove the specified *section* from the configuration. If the section in fact
315 existed, return ``True``. Otherwise return ``False``.
316
317
318.. method:: RawConfigParser.optionxform(option)
319
Georg Brandl495f7b52009-10-27 15:28:25 +0000320 Transforms the option name *option* as found in an input file or as passed in
321 by client code to the form that should be used in the internal structures.
322 The default implementation returns a lower-case version of *option*;
323 subclasses may override this or client code can set an attribute of this name
324 on instances to affect this behavior.
325
326 You don't necessarily need to subclass a ConfigParser to use this method, you
327 can also re-set it on an instance, to a function that takes a string
328 argument. Setting it to ``str``, for example, would make option names case
329 sensitive::
330
331 cfgparser = ConfigParser()
332 ...
333 cfgparser.optionxform = str
334
335 Note that when reading configuration files, whitespace around the
336 option names are stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338
339.. _configparser-objects:
340
341ConfigParser Objects
342--------------------
343
344The :class:`ConfigParser` class extends some methods of the
345:class:`RawConfigParser` interface, adding some optional arguments.
346
347
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000348.. method:: ConfigParser.get(section, option, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350 Get an *option* value for the named *section*. All the ``'%'`` interpolations
351 are expanded in the return values, based on the defaults passed into the
352 constructor, as well as the options *vars* provided, unless the *raw* argument
353 is true.
354
355
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000356.. method:: ConfigParser.items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000357
358 Return a list of ``(name, value)`` pairs for each option in the given *section*.
359 Optional arguments have the same meaning as for the :meth:`get` method.
360
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362.. _safeconfigparser-objects:
363
364SafeConfigParser Objects
365------------------------
366
367The :class:`SafeConfigParser` class implements the same extended interface as
368:class:`ConfigParser`, with the following addition:
369
370
371.. method:: SafeConfigParser.set(section, option, value)
372
373 If the given section exists, set the given option to the specified value;
Georg Brandlf6945182008-02-01 11:56:49 +0000374 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
375 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000377
378Examples
379--------
380
381An example of writing to a configuration file::
382
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000383 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000384
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000385 config = configparser.RawConfigParser()
Georg Brandl48310cd2009-01-03 21:18:54 +0000386
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000387 # When adding sections or items, add them in the reverse order of
388 # how you want them to be displayed in the actual file.
389 # In addition, please note that using RawConfigParser's and the raw
390 # mode of ConfigParser's respective set functions, you can assign
391 # non-string values to keys internally, but will receive an error
392 # when attempting to write to a file or when you get it in non-raw
393 # mode. SafeConfigParser does not allow such assignments to take place.
394 config.add_section('Section1')
395 config.set('Section1', 'int', '15')
396 config.set('Section1', 'bool', 'true')
397 config.set('Section1', 'float', '3.1415')
398 config.set('Section1', 'baz', 'fun')
399 config.set('Section1', 'bar', 'Python')
400 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl48310cd2009-01-03 21:18:54 +0000401
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000402 # Writing our configuration file to 'example.cfg'
Georg Brandl73753d32009-09-22 13:53:14 +0000403 with open('example.cfg', 'w') as configfile:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000404 config.write(configfile)
405
406An example of reading the configuration file again::
407
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000408 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000409
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000410 config = configparser.RawConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000411 config.read('example.cfg')
412
413 # getfloat() raises an exception if the value is not a float
414 # getint() and getboolean() also do this for their respective types
415 float = config.getfloat('Section1', 'float')
416 int = config.getint('Section1', 'int')
Georg Brandlf6945182008-02-01 11:56:49 +0000417 print(float + int)
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000418
419 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
420 # This is because we are using a RawConfigParser().
421 if config.getboolean('Section1', 'bool'):
Georg Brandlf6945182008-02-01 11:56:49 +0000422 print(config.get('Section1', 'foo'))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000423
424To get interpolation, you will need to use a :class:`ConfigParser` or
425:class:`SafeConfigParser`::
426
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000427 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000428
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000429 config = configparser.ConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000430 config.read('example.cfg')
431
432 # Set the third, optional argument of get to 1 if you wish to use raw mode.
Georg Brandlf6945182008-02-01 11:56:49 +0000433 print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
434 print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000435
436 # The optional fourth argument is a dict with members that will take
437 # precedence in interpolation.
Georg Brandlf6945182008-02-01 11:56:49 +0000438 print(config.get('Section1', 'foo', 0, {'bar': 'Documentation',
439 'baz': 'evil'}))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000440
Georg Brandl48310cd2009-01-03 21:18:54 +0000441Defaults are available in all three types of ConfigParsers. They are used in
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000442interpolation if an option used is not defined elsewhere. ::
443
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000444 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000445
446 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000447 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000448 config.read('example.cfg')
Georg Brandl48310cd2009-01-03 21:18:54 +0000449
Georg Brandlf6945182008-02-01 11:56:49 +0000450 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000451 config.remove_option('Section1', 'bar')
452 config.remove_option('Section1', 'baz')
Georg Brandlf6945182008-02-01 11:56:49 +0000453 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000454
455The function ``opt_move`` below can be used to move options between sections::
456
457 def opt_move(config, section1, section2, option):
458 try:
459 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000460 except configparser.NoSectionError:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000461 # Create non-existent section
462 config.add_section(section2)
463 opt_move(config, section1, section2, option)
Georg Brandl86def6c2008-01-21 20:36:10 +0000464 else:
465 config.remove_option(section1, option)
Fred Drake03c44a32010-02-19 06:08:41 +0000466
467Some configuration files are known to include settings without values, but which
468otherwise conform to the syntax supported by :mod:`configparser`. The
469*allow_no_value* parameter to the constructor can be used to indicate that such
470values should be accepted:
471
472.. doctest::
473
474 >>> import configparser
475 >>> import io
476
477 >>> sample_config = """
478 ... [mysqld]
479 ... user = mysql
480 ... pid-file = /var/run/mysqld/mysqld.pid
481 ... skip-external-locking
482 ... old_passwords = 1
483 ... skip-bdb
484 ... skip-innodb
485 ... """
486 >>> config = configparser.RawConfigParser(allow_no_value=True)
487 >>> config.readfp(io.BytesIO(sample_config))
488
489 >>> # Settings with values are treated as before:
490 >>> config.get("mysqld", "user")
491 'mysql'
492
493 >>> # Settings without values provide None:
494 >>> config.get("mysqld", "skip-bdb")
495
496 >>> # Settings which aren't specified still raise an error:
497 >>> config.get("mysqld", "does-not-exist")
498 Traceback (most recent call last):
499 ...
500 configparser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'