blob: 4b1e7a02a69c8fbd906af2e5d9405aa525c23ef5 [file] [log] [blame]
Georg Brandl392c6fc2008-05-25 07:25:25 +00001:mod:`ConfigParser` --- Configuration file parser
Georg Brandl8ec7f652007-08-15 14:28:01 +00002=================================================
3
Alexandre Vassalottic92fef92008-05-14 22:51:10 +00004.. module:: ConfigParser
Georg Brandl8ec7f652007-08-15 14:28:01 +00005 :synopsis: Configuration file parser.
Alexandre Vassalottie2514c62008-05-14 22:44:22 +00006
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Alexandre Vassalottic92fef92008-05-14 22:51:10 +000012.. note::
Georg Brandl392c6fc2008-05-25 07:25:25 +000013
Georg Brandle92818f2009-01-03 20:47:01 +000014 The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in
15 Python 3.0. The :term:`2to3` tool will automatically adapt imports when
16 converting your sources to 3.0.
Alexandre Vassalottic92fef92008-05-14 22:51:10 +000017
Georg Brandl8ec7f652007-08-15 14:28:01 +000018.. index::
19 pair: .ini; file
20 pair: configuration; file
21 single: ini file
22 single: Windows ini file
23
24This module defines the class :class:`ConfigParser`. The :class:`ConfigParser`
25class implements a basic configuration file parser language which provides a
26structure similar to what you would find on Microsoft Windows INI files. You
27can use this to write Python programs which can be customized by end users
28easily.
29
Georg Brandl16a57f62009-04-27 15:29:09 +000030.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
Georg Brandl16a57f62009-04-27 15:29:09 +000032 This library does *not* interpret or write the value-type prefixes used in
33 the Windows Registry extended version of INI syntax.
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
35The configuration file consists of sections, led by a ``[section]`` header and
36followed by ``name: value`` entries, with continuations in the style of
Georg Brandl27f43742008-03-26 09:32:46 +000037:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
38accepted. Note that leading whitespace is removed from values. The optional
39values can contain format strings which refer to other values in the same
40section, or values in a special ``DEFAULT`` section. Additional defaults can be
41provided on initialization and retrieval. Lines beginning with ``'#'`` or
42``';'`` are ignored and may be used to provide comments.
Georg Brandl8ec7f652007-08-15 14:28:01 +000043
Georg Brandld070cc52010-08-01 21:06:46 +000044Configuration files may include comments, prefixed by specific characters (``#``
45and ``;``). Comments may appear on their own in an otherwise empty line, or may
Fred Drake9a9aa202010-11-09 13:33:21 +000046be entered in lines holding values or section names. In the latter case, they
Georg Brandld070cc52010-08-01 21:06:46 +000047need to be preceded by a whitespace character to be recognized as a comment.
48(For backwards compatibility, only ``;`` starts an inline comment, while ``#``
49does not.)
50
51On top of the core functionality, :class:`SafeConfigParser` supports
52interpolation. This means values can contain format strings which refer to
53other values in the same section, or values in a special ``DEFAULT`` section.
54Additional defaults can be provided on initialization.
55
Georg Brandl8ec7f652007-08-15 14:28:01 +000056For example::
57
58 [My Section]
59 foodir: %(dir)s/whatever
60 dir=frob
Georg Brandl27f43742008-03-26 09:32:46 +000061 long: this value continues
62 in the next line
Georg Brandl8ec7f652007-08-15 14:28:01 +000063
64would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
65All reference expansions are done on demand.
66
67Default values can be specified by passing them into the :class:`ConfigParser`
68constructor as a dictionary. Additional defaults may be passed into the
69:meth:`get` method which will override all others.
70
Georg Brandld7d4fd72009-07-26 14:37:28 +000071Sections are normally stored in a built-in dictionary. An alternative dictionary
Georg Brandl8ec7f652007-08-15 14:28:01 +000072type can be passed to the :class:`ConfigParser` constructor. For example, if a
73dictionary type is passed that sorts its keys, the sections will be sorted on
74write-back, as will be the keys within each section.
75
76
Fred Drakecc43b562010-02-19 05:24:30 +000077.. class:: RawConfigParser([defaults[, dict_type[, allow_no_value]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000078
79 The basic configuration object. When *defaults* is given, it is initialized
80 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
81 be used to create the dictionary objects for the list of sections, for the
Fred Drakecc43b562010-02-19 05:24:30 +000082 options within a section, and for the default values. When *allow_no_value*
83 is true (default: ``False``), options without values are accepted; the value
84 presented for these is ``None``.
85
86 This class does not
Georg Brandl8ec7f652007-08-15 14:28:01 +000087 support the magical interpolation behavior.
88
89 .. versionadded:: 2.3
90
91 .. versionchanged:: 2.6
92 *dict_type* was added.
93
Raymond Hettingere89b8e92009-03-03 05:00:37 +000094 .. versionchanged:: 2.7
95 The default *dict_type* is :class:`collections.OrderedDict`.
Fred Drakecc43b562010-02-19 05:24:30 +000096 *allow_no_value* was added.
Raymond Hettingere89b8e92009-03-03 05:00:37 +000097
Georg Brandl8ec7f652007-08-15 14:28:01 +000098
Fred Drakecc43b562010-02-19 05:24:30 +000099.. class:: ConfigParser([defaults[, dict_type[, allow_no_value]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000100
101 Derived class of :class:`RawConfigParser` that implements the magical
102 interpolation feature and adds optional arguments to the :meth:`get` and
103 :meth:`items` methods. The values in *defaults* must be appropriate for the
104 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
105 its value is the section name, and will override any value provided in
106 *defaults*.
107
108 All option names used in interpolation will be passed through the
109 :meth:`optionxform` method just like any other option name reference. For
110 example, using the default implementation of :meth:`optionxform` (which converts
111 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
112 equivalent.
113
Raymond Hettingere89b8e92009-03-03 05:00:37 +0000114 .. versionadded:: 2.3
115
116 .. versionchanged:: 2.6
117 *dict_type* was added.
118
119 .. versionchanged:: 2.7
120 The default *dict_type* is :class:`collections.OrderedDict`.
Fred Drakecc43b562010-02-19 05:24:30 +0000121 *allow_no_value* was added.
Raymond Hettingere89b8e92009-03-03 05:00:37 +0000122
Georg Brandl8ec7f652007-08-15 14:28:01 +0000123
Fred Drakecc43b562010-02-19 05:24:30 +0000124.. class:: SafeConfigParser([defaults[, dict_type[, allow_no_value]]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125
126 Derived class of :class:`ConfigParser` that implements a more-sane variant of
127 the magical interpolation feature. This implementation is more predictable as
128 well. New applications should prefer this version if they don't need to be
129 compatible with older versions of Python.
130
Georg Brandlb19be572007-12-29 10:57:00 +0000131 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132
133 .. versionadded:: 2.3
134
Raymond Hettingere89b8e92009-03-03 05:00:37 +0000135 .. versionchanged:: 2.6
136 *dict_type* was added.
137
138 .. versionchanged:: 2.7
139 The default *dict_type* is :class:`collections.OrderedDict`.
Fred Drakecc43b562010-02-19 05:24:30 +0000140 *allow_no_value* was added.
Raymond Hettingere89b8e92009-03-03 05:00:37 +0000141
Georg Brandl8ec7f652007-08-15 14:28:01 +0000142
Georg Brandld070cc52010-08-01 21:06:46 +0000143.. exception:: Error
144
145 Base class for all other configparser exceptions.
146
147
Georg Brandl8ec7f652007-08-15 14:28:01 +0000148.. exception:: NoSectionError
149
150 Exception raised when a specified section is not found.
151
152
153.. exception:: DuplicateSectionError
154
155 Exception raised if :meth:`add_section` is called with the name of a section
156 that is already present.
157
158
159.. exception:: NoOptionError
160
161 Exception raised when a specified option is not found in the specified section.
162
163
164.. exception:: InterpolationError
165
166 Base class for exceptions raised when problems occur performing string
167 interpolation.
168
169
170.. exception:: InterpolationDepthError
171
172 Exception raised when string interpolation cannot be completed because the
173 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
174 :exc:`InterpolationError`.
175
176
177.. exception:: InterpolationMissingOptionError
178
179 Exception raised when an option referenced from a value does not exist. Subclass
180 of :exc:`InterpolationError`.
181
182 .. versionadded:: 2.3
183
184
185.. exception:: InterpolationSyntaxError
186
187 Exception raised when the source text into which substitutions are made does not
188 conform to the required syntax. Subclass of :exc:`InterpolationError`.
189
190 .. versionadded:: 2.3
191
192
193.. exception:: MissingSectionHeaderError
194
195 Exception raised when attempting to parse a file which has no section headers.
196
197
198.. exception:: ParsingError
199
200 Exception raised when errors occur attempting to parse a file.
201
202
203.. data:: MAX_INTERPOLATION_DEPTH
204
205 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
206 parameter is false. This is relevant only for the :class:`ConfigParser` class.
207
208
209.. seealso::
210
211 Module :mod:`shlex`
212 Support for a creating Unix shell-like mini-languages which can be used as an
213 alternate format for application configuration files.
214
215
216.. _rawconfigparser-objects:
217
218RawConfigParser Objects
219-----------------------
220
221:class:`RawConfigParser` instances have the following methods:
222
223
224.. method:: RawConfigParser.defaults()
225
226 Return a dictionary containing the instance-wide defaults.
227
228
229.. method:: RawConfigParser.sections()
230
231 Return a list of the sections available; ``DEFAULT`` is not included in the
232 list.
233
234
235.. method:: RawConfigParser.add_section(section)
236
237 Add a section named *section* to the instance. If a section by the given name
Facundo Batistab12f0b52008-02-23 12:46:10 +0000238 already exists, :exc:`DuplicateSectionError` is raised. If the name
239 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
240 :exc:`ValueError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241
242.. method:: RawConfigParser.has_section(section)
243
244 Indicates whether the named section is present in the configuration. The
245 ``DEFAULT`` section is not acknowledged.
246
247
248.. method:: RawConfigParser.options(section)
249
250 Returns a list of options available in the specified *section*.
251
252
253.. method:: RawConfigParser.has_option(section, option)
254
255 If the given section exists, and contains the given option, return
256 :const:`True`; otherwise return :const:`False`.
257
258 .. versionadded:: 1.6
259
260
261.. method:: RawConfigParser.read(filenames)
262
263 Attempt to read and parse a list of filenames, returning a list of filenames
264 which were successfully parsed. If *filenames* is a string or Unicode string,
265 it is treated as a single filename. If a file named in *filenames* cannot be
266 opened, that file will be ignored. This is designed so that you can specify a
267 list of potential configuration file locations (for example, the current
268 directory, the user's home directory, and some system-wide directory), and all
269 existing configuration files in the list will be read. If none of the named
270 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
271 An application which requires initial values to be loaded from a file should
272 load the required file or files using :meth:`readfp` before calling :meth:`read`
273 for any optional files::
274
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000275 import ConfigParser, os
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276
Georg Brandl392c6fc2008-05-25 07:25:25 +0000277 config = ConfigParser.ConfigParser()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000278 config.readfp(open('defaults.cfg'))
279 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
280
281 .. versionchanged:: 2.4
282 Returns list of successfully parsed filenames.
283
284
285.. method:: RawConfigParser.readfp(fp[, filename])
286
287 Read and parse configuration data from the file or file-like object in *fp*
288 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
289 has a :attr:`name` attribute, that is used for *filename*; the default is
290 ``<???>``.
291
292
293.. method:: RawConfigParser.get(section, option)
294
295 Get an *option* value for the named *section*.
296
297
298.. method:: RawConfigParser.getint(section, option)
299
300 A convenience method which coerces the *option* in the specified *section* to an
301 integer.
302
303
304.. method:: RawConfigParser.getfloat(section, option)
305
306 A convenience method which coerces the *option* in the specified *section* to a
307 floating point number.
308
309
310.. method:: RawConfigParser.getboolean(section, option)
311
312 A convenience method which coerces the *option* in the specified *section* to a
313 Boolean value. Note that the accepted values for the option are ``"1"``,
314 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
315 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
316 ``False``. These string values are checked in a case-insensitive manner. Any
317 other value will cause it to raise :exc:`ValueError`.
318
319
320.. method:: RawConfigParser.items(section)
321
322 Return a list of ``(name, value)`` pairs for each option in the given *section*.
323
324
325.. method:: RawConfigParser.set(section, option, value)
326
327 If the given section exists, set the given option to the specified value;
328 otherwise raise :exc:`NoSectionError`. While it is possible to use
329 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
330 true) for *internal* storage of non-string values, full functionality (including
331 interpolation and output to files) can only be achieved using string values.
332
333 .. versionadded:: 1.6
334
335
336.. method:: RawConfigParser.write(fileobject)
337
338 Write a representation of the configuration to the specified file object. This
339 representation can be parsed by a future :meth:`read` call.
340
341 .. versionadded:: 1.6
342
343
344.. method:: RawConfigParser.remove_option(section, option)
345
346 Remove the specified *option* from the specified *section*. If the section does
347 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
348 return :const:`True`; otherwise return :const:`False`.
349
350 .. versionadded:: 1.6
351
352
353.. method:: RawConfigParser.remove_section(section)
354
355 Remove the specified *section* from the configuration. If the section in fact
356 existed, return ``True``. Otherwise return ``False``.
357
358
359.. method:: RawConfigParser.optionxform(option)
360
Georg Brandldc020522009-10-23 08:14:44 +0000361 Transforms the option name *option* as found in an input file or as passed in
362 by client code to the form that should be used in the internal structures.
363 The default implementation returns a lower-case version of *option*;
364 subclasses may override this or client code can set an attribute of this name
365 on instances to affect this behavior.
366
367 You don't necessarily need to subclass a ConfigParser to use this method, you
368 can also re-set it on an instance, to a function that takes a string
369 argument. Setting it to ``str``, for example, would make option names case
370 sensitive::
371
372 cfgparser = ConfigParser()
373 ...
374 cfgparser.optionxform = str
Georg Brandl8ec7f652007-08-15 14:28:01 +0000375
Fred Draked617cba2009-10-23 13:04:51 +0000376 Note that when reading configuration files, whitespace around the
Georg Brandl5460ff92009-10-24 10:04:19 +0000377 option names are stripped before :meth:`optionxform` is called.
Fred Draked617cba2009-10-23 13:04:51 +0000378
Georg Brandl8ec7f652007-08-15 14:28:01 +0000379
380.. _configparser-objects:
381
382ConfigParser Objects
383--------------------
384
385The :class:`ConfigParser` class extends some methods of the
386:class:`RawConfigParser` interface, adding some optional arguments.
387
388
389.. method:: ConfigParser.get(section, option[, raw[, vars]])
390
Georg Brandld070cc52010-08-01 21:06:46 +0000391 Get an *option* value for the named *section*. If *vars* is provided, it
392 must be a dictionary. The *option* is looked up in *vars* (if provided),
393 *section*, and in *defaults* in that order.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000394
Georg Brandld070cc52010-08-01 21:06:46 +0000395 All the ``'%'`` interpolations are expanded in the return values, unless the
396 *raw* argument is true. Values for interpolation keys are looked up in the
397 same manner as the option.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398
399.. method:: ConfigParser.items(section[, raw[, vars]])
400
401 Return a list of ``(name, value)`` pairs for each option in the given *section*.
402 Optional arguments have the same meaning as for the :meth:`get` method.
403
404 .. versionadded:: 2.3
405
406
407.. _safeconfigparser-objects:
408
409SafeConfigParser Objects
410------------------------
411
412The :class:`SafeConfigParser` class implements the same extended interface as
413:class:`ConfigParser`, with the following addition:
414
415
416.. method:: SafeConfigParser.set(section, option, value)
417
418 If the given section exists, set the given option to the specified value;
419 otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str`
420 or :class:`unicode`); if not, :exc:`TypeError` is raised.
421
422 .. versionadded:: 2.4
423
Georg Brandl430e3622007-11-29 17:02:34 +0000424
425Examples
426--------
427
428An example of writing to a configuration file::
429
Georg Brandl392c6fc2008-05-25 07:25:25 +0000430 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000431
Georg Brandl392c6fc2008-05-25 07:25:25 +0000432 config = ConfigParser.RawConfigParser()
433
Georg Brandl430e3622007-11-29 17:02:34 +0000434 # When adding sections or items, add them in the reverse order of
435 # how you want them to be displayed in the actual file.
436 # In addition, please note that using RawConfigParser's and the raw
437 # mode of ConfigParser's respective set functions, you can assign
438 # non-string values to keys internally, but will receive an error
439 # when attempting to write to a file or when you get it in non-raw
440 # mode. SafeConfigParser does not allow such assignments to take place.
441 config.add_section('Section1')
442 config.set('Section1', 'int', '15')
443 config.set('Section1', 'bool', 'true')
444 config.set('Section1', 'float', '3.1415')
445 config.set('Section1', 'baz', 'fun')
446 config.set('Section1', 'bar', 'Python')
447 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl392c6fc2008-05-25 07:25:25 +0000448
Georg Brandl430e3622007-11-29 17:02:34 +0000449 # Writing our configuration file to 'example.cfg'
450 with open('example.cfg', 'wb') as configfile:
451 config.write(configfile)
452
453An example of reading the configuration file again::
454
Georg Brandl392c6fc2008-05-25 07:25:25 +0000455 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000456
Georg Brandl392c6fc2008-05-25 07:25:25 +0000457 config = ConfigParser.RawConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000458 config.read('example.cfg')
459
460 # getfloat() raises an exception if the value is not a float
461 # getint() and getboolean() also do this for their respective types
462 float = config.getfloat('Section1', 'float')
463 int = config.getint('Section1', 'int')
464 print float + int
465
466 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
467 # This is because we are using a RawConfigParser().
468 if config.getboolean('Section1', 'bool'):
469 print config.get('Section1', 'foo')
470
471To get interpolation, you will need to use a :class:`ConfigParser` or
472:class:`SafeConfigParser`::
473
Georg Brandl392c6fc2008-05-25 07:25:25 +0000474 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000475
Georg Brandl392c6fc2008-05-25 07:25:25 +0000476 config = ConfigParser.ConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000477 config.read('example.cfg')
478
479 # Set the third, optional argument of get to 1 if you wish to use raw mode.
480 print config.get('Section1', 'foo', 0) # -> "Python is fun!"
481 print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
482
483 # The optional fourth argument is a dict with members that will take
484 # precedence in interpolation.
485 print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
486 'baz': 'evil'})
487
Georg Brandl392c6fc2008-05-25 07:25:25 +0000488Defaults are available in all three types of ConfigParsers. They are used in
Georg Brandl430e3622007-11-29 17:02:34 +0000489interpolation if an option used is not defined elsewhere. ::
490
Georg Brandl392c6fc2008-05-25 07:25:25 +0000491 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000492
493 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Georg Brandl392c6fc2008-05-25 07:25:25 +0000494 config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Georg Brandl430e3622007-11-29 17:02:34 +0000495 config.read('example.cfg')
Georg Brandl392c6fc2008-05-25 07:25:25 +0000496
Georg Brandl430e3622007-11-29 17:02:34 +0000497 print config.get('Section1', 'foo') # -> "Python is fun!"
498 config.remove_option('Section1', 'bar')
499 config.remove_option('Section1', 'baz')
500 print config.get('Section1', 'foo') # -> "Life is hard!"
501
502The function ``opt_move`` below can be used to move options between sections::
503
504 def opt_move(config, section1, section2, option):
505 try:
506 config.set(section2, option, config.get(section1, option, 1))
Georg Brandl392c6fc2008-05-25 07:25:25 +0000507 except ConfigParser.NoSectionError:
Georg Brandl430e3622007-11-29 17:02:34 +0000508 # Create non-existent section
509 config.add_section(section2)
510 opt_move(config, section1, section2, option)
Georg Brandl960b1862008-01-21 16:28:13 +0000511 else:
512 config.remove_option(section1, option)
Fred Drakecc43b562010-02-19 05:24:30 +0000513
514Some configuration files are known to include settings without values, but which
515otherwise conform to the syntax supported by :mod:`ConfigParser`. The
516*allow_no_value* parameter to the constructor can be used to indicate that such
517values should be accepted:
518
519.. doctest::
520
521 >>> import ConfigParser
522 >>> import io
523
524 >>> sample_config = """
525 ... [mysqld]
526 ... user = mysql
527 ... pid-file = /var/run/mysqld/mysqld.pid
528 ... skip-external-locking
529 ... old_passwords = 1
530 ... skip-bdb
531 ... skip-innodb
532 ... """
533 >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
534 >>> config.readfp(io.BytesIO(sample_config))
535
536 >>> # Settings with values are treated as before:
537 >>> config.get("mysqld", "user")
538 'mysql'
539
540 >>> # Settings without values provide None:
541 >>> config.get("mysqld", "skip-bdb")
542
543 >>> # Settings which aren't specified still raise an error:
544 >>> config.get("mysqld", "does-not-exist")
545 Traceback (most recent call last):
546 ...
547 ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'