blob: 7f68de762ff95289a8e850de66689da97609b0b1 [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 Brandl734373c2009-01-03 21:55:17 +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 Brandl38853142009-04-28 18:23:28 +000030.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
Georg Brandl38853142009-04-28 18:23:28 +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 Brandl6290bcf2010-08-01 21:48:47 +000044Configuration files may include comments, prefixed by specific characters (``#``
45and ``;``). Comments may appear on their own in an otherwise empty line, or may
46be entered in lines holding values or spection names. In the latter case, they
47need 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 Brandl4ae4f872009-10-27 14:37:48 +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
77.. class:: RawConfigParser([defaults[, dict_type]])
78
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
Łukasz Langa22108f12011-04-28 17:27:59 +020082 options within a section, and for the default values. This class does not
Georg Brandl8ec7f652007-08-15 14:28:01 +000083 support the magical interpolation behavior.
84
Łukasz Langa22108f12011-04-28 17:27:59 +020085 All option names are passed through the :meth:`optionxform` method. Its
86 default implementation converts option names to lower case.
87
Georg Brandl8ec7f652007-08-15 14:28:01 +000088 .. versionadded:: 2.3
89
90 .. versionchanged:: 2.6
91 *dict_type* was added.
92
93
Raymond Hettinger4a9fda42009-03-01 02:07:25 +000094.. class:: ConfigParser([defaults[, dict_type]])
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
96 Derived class of :class:`RawConfigParser` that implements the magical
97 interpolation feature and adds optional arguments to the :meth:`get` and
98 :meth:`items` methods. The values in *defaults* must be appropriate for the
99 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
100 its value is the section name, and will override any value provided in
101 *defaults*.
102
103 All option names used in interpolation will be passed through the
Łukasz Langa22108f12011-04-28 17:27:59 +0200104 :meth:`optionxform` method just like any other option name reference. Using
105 the default implementation of :meth:`optionxform`, the values ``foo %(bar)s``
106 and ``foo %(BAR)s`` are equivalent.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000107
108
Raymond Hettinger4a9fda42009-03-01 02:07:25 +0000109.. class:: SafeConfigParser([defaults[, dict_type]])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000110
111 Derived class of :class:`ConfigParser` that implements a more-sane variant of
112 the magical interpolation feature. This implementation is more predictable as
113 well. New applications should prefer this version if they don't need to be
114 compatible with older versions of Python.
115
Georg Brandlb19be572007-12-29 10:57:00 +0000116 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000117
118 .. versionadded:: 2.3
119
120
Georg Brandl6290bcf2010-08-01 21:48:47 +0000121.. exception:: Error
122
123 Base class for all other configparser exceptions.
124
125
Georg Brandl8ec7f652007-08-15 14:28:01 +0000126.. exception:: NoSectionError
127
128 Exception raised when a specified section is not found.
129
130
131.. exception:: DuplicateSectionError
132
133 Exception raised if :meth:`add_section` is called with the name of a section
134 that is already present.
135
136
137.. exception:: NoOptionError
138
139 Exception raised when a specified option is not found in the specified section.
140
141
142.. exception:: InterpolationError
143
144 Base class for exceptions raised when problems occur performing string
145 interpolation.
146
147
148.. exception:: InterpolationDepthError
149
150 Exception raised when string interpolation cannot be completed because the
151 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
152 :exc:`InterpolationError`.
153
154
155.. exception:: InterpolationMissingOptionError
156
157 Exception raised when an option referenced from a value does not exist. Subclass
158 of :exc:`InterpolationError`.
159
160 .. versionadded:: 2.3
161
162
163.. exception:: InterpolationSyntaxError
164
165 Exception raised when the source text into which substitutions are made does not
166 conform to the required syntax. Subclass of :exc:`InterpolationError`.
167
168 .. versionadded:: 2.3
169
170
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
Facundo Batistab12f0b52008-02-23 12:46:10 +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 Brandl8ec7f652007-08-15 14:28:01 +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
236 .. versionadded:: 1.6
237
238
239.. method:: RawConfigParser.read(filenames)
240
241 Attempt to read and parse a list of filenames, returning a list of filenames
242 which were successfully parsed. If *filenames* is a string or Unicode string,
243 it is treated as a single filename. If a file named in *filenames* cannot be
244 opened, that file will be ignored. This is designed so that you can specify a
245 list of potential configuration file locations (for example, the current
246 directory, the user's home directory, and some system-wide directory), and all
247 existing configuration files in the list will be read. If none of the named
248 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
249 An application which requires initial values to be loaded from a file should
250 load the required file or files using :meth:`readfp` before calling :meth:`read`
251 for any optional files::
252
Georg Brandl392c6fc2008-05-25 07:25:25 +0000253 import ConfigParser, os
Georg Brandl8ec7f652007-08-15 14:28:01 +0000254
Georg Brandl392c6fc2008-05-25 07:25:25 +0000255 config = ConfigParser.ConfigParser()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256 config.readfp(open('defaults.cfg'))
257 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
258
259 .. versionchanged:: 2.4
260 Returns list of successfully parsed filenames.
261
262
263.. method:: RawConfigParser.readfp(fp[, filename])
264
265 Read and parse configuration data from the file or file-like object in *fp*
266 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
267 has a :attr:`name` attribute, that is used for *filename*; the default is
268 ``<???>``.
269
270
271.. method:: RawConfigParser.get(section, option)
272
273 Get an *option* value for the named *section*.
274
275
276.. method:: RawConfigParser.getint(section, option)
277
278 A convenience method which coerces the *option* in the specified *section* to an
279 integer.
280
281
282.. method:: RawConfigParser.getfloat(section, option)
283
284 A convenience method which coerces the *option* in the specified *section* to a
285 floating point number.
286
287
288.. method:: RawConfigParser.getboolean(section, option)
289
290 A convenience method which coerces the *option* in the specified *section* to a
291 Boolean value. Note that the accepted values for the option are ``"1"``,
292 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
293 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
294 ``False``. These string values are checked in a case-insensitive manner. Any
295 other value will cause it to raise :exc:`ValueError`.
296
297
298.. method:: RawConfigParser.items(section)
299
300 Return a list of ``(name, value)`` pairs for each option in the given *section*.
301
302
303.. method:: RawConfigParser.set(section, option, value)
304
305 If the given section exists, set the given option to the specified value;
306 otherwise raise :exc:`NoSectionError`. While it is possible to use
307 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
308 true) for *internal* storage of non-string values, full functionality (including
309 interpolation and output to files) can only be achieved using string values.
310
311 .. versionadded:: 1.6
312
313
314.. method:: RawConfigParser.write(fileobject)
315
316 Write a representation of the configuration to the specified file object. This
317 representation can be parsed by a future :meth:`read` call.
318
319 .. versionadded:: 1.6
320
321
322.. method:: RawConfigParser.remove_option(section, option)
323
324 Remove the specified *option* from the specified *section*. If the section does
325 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
326 return :const:`True`; otherwise return :const:`False`.
327
328 .. versionadded:: 1.6
329
330
331.. method:: RawConfigParser.remove_section(section)
332
333 Remove the specified *section* from the configuration. If the section in fact
334 existed, return ``True``. Otherwise return ``False``.
335
336
337.. method:: RawConfigParser.optionxform(option)
338
Georg Brandl5d2eb342009-10-27 15:08:27 +0000339 Transforms the option name *option* as found in an input file or as passed in
340 by client code to the form that should be used in the internal structures.
341 The default implementation returns a lower-case version of *option*;
342 subclasses may override this or client code can set an attribute of this name
343 on instances to affect this behavior.
344
345 You don't necessarily need to subclass a ConfigParser to use this method, you
346 can also re-set it on an instance, to a function that takes a string
347 argument. Setting it to ``str``, for example, would make option names case
348 sensitive::
349
350 cfgparser = ConfigParser()
351 ...
352 cfgparser.optionxform = str
353
354 Note that when reading configuration files, whitespace around the
355 option names are stripped before :meth:`optionxform` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000356
357
358.. _configparser-objects:
359
360ConfigParser Objects
361--------------------
362
363The :class:`ConfigParser` class extends some methods of the
364:class:`RawConfigParser` interface, adding some optional arguments.
365
366
367.. method:: ConfigParser.get(section, option[, raw[, vars]])
368
Georg Brandl6290bcf2010-08-01 21:48:47 +0000369 Get an *option* value for the named *section*. If *vars* is provided, it
370 must be a dictionary. The *option* is looked up in *vars* (if provided),
371 *section*, and in *defaults* in that order.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000372
Georg Brandl6290bcf2010-08-01 21:48:47 +0000373 All the ``'%'`` interpolations are expanded in the return values, unless the
374 *raw* argument is true. Values for interpolation keys are looked up in the
375 same manner as the option.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000376
377.. method:: ConfigParser.items(section[, raw[, vars]])
378
379 Return a list of ``(name, value)`` pairs for each option in the given *section*.
380 Optional arguments have the same meaning as for the :meth:`get` method.
381
382 .. versionadded:: 2.3
383
384
385.. _safeconfigparser-objects:
386
387SafeConfigParser Objects
388------------------------
389
390The :class:`SafeConfigParser` class implements the same extended interface as
391:class:`ConfigParser`, with the following addition:
392
393
394.. method:: SafeConfigParser.set(section, option, value)
395
396 If the given section exists, set the given option to the specified value;
397 otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str`
398 or :class:`unicode`); if not, :exc:`TypeError` is raised.
399
400 .. versionadded:: 2.4
401
Georg Brandl430e3622007-11-29 17:02:34 +0000402
403Examples
404--------
405
406An example of writing to a configuration file::
407
Georg Brandl392c6fc2008-05-25 07:25:25 +0000408 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000409
Georg Brandl392c6fc2008-05-25 07:25:25 +0000410 config = ConfigParser.RawConfigParser()
411
Georg Brandl430e3622007-11-29 17:02:34 +0000412 # When adding sections or items, add them in the reverse order of
413 # how you want them to be displayed in the actual file.
414 # In addition, please note that using RawConfigParser's and the raw
415 # mode of ConfigParser's respective set functions, you can assign
416 # non-string values to keys internally, but will receive an error
417 # when attempting to write to a file or when you get it in non-raw
418 # mode. SafeConfigParser does not allow such assignments to take place.
419 config.add_section('Section1')
420 config.set('Section1', 'int', '15')
421 config.set('Section1', 'bool', 'true')
422 config.set('Section1', 'float', '3.1415')
423 config.set('Section1', 'baz', 'fun')
424 config.set('Section1', 'bar', 'Python')
425 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl392c6fc2008-05-25 07:25:25 +0000426
Georg Brandl430e3622007-11-29 17:02:34 +0000427 # Writing our configuration file to 'example.cfg'
428 with open('example.cfg', 'wb') as configfile:
429 config.write(configfile)
430
431An example of reading the configuration file again::
432
Georg Brandl392c6fc2008-05-25 07:25:25 +0000433 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000434
Georg Brandl392c6fc2008-05-25 07:25:25 +0000435 config = ConfigParser.RawConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000436 config.read('example.cfg')
437
438 # getfloat() raises an exception if the value is not a float
439 # getint() and getboolean() also do this for their respective types
440 float = config.getfloat('Section1', 'float')
441 int = config.getint('Section1', 'int')
442 print float + int
443
444 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
445 # This is because we are using a RawConfigParser().
446 if config.getboolean('Section1', 'bool'):
447 print config.get('Section1', 'foo')
448
449To get interpolation, you will need to use a :class:`ConfigParser` or
450:class:`SafeConfigParser`::
451
Georg Brandl392c6fc2008-05-25 07:25:25 +0000452 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000453
Georg Brandl392c6fc2008-05-25 07:25:25 +0000454 config = ConfigParser.ConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000455 config.read('example.cfg')
456
457 # Set the third, optional argument of get to 1 if you wish to use raw mode.
458 print config.get('Section1', 'foo', 0) # -> "Python is fun!"
459 print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
460
461 # The optional fourth argument is a dict with members that will take
462 # precedence in interpolation.
463 print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
464 'baz': 'evil'})
465
Georg Brandl392c6fc2008-05-25 07:25:25 +0000466Defaults are available in all three types of ConfigParsers. They are used in
Georg Brandl430e3622007-11-29 17:02:34 +0000467interpolation if an option used is not defined elsewhere. ::
468
Georg Brandl392c6fc2008-05-25 07:25:25 +0000469 import ConfigParser
Georg Brandl430e3622007-11-29 17:02:34 +0000470
471 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Georg Brandl392c6fc2008-05-25 07:25:25 +0000472 config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Georg Brandl430e3622007-11-29 17:02:34 +0000473 config.read('example.cfg')
Georg Brandl392c6fc2008-05-25 07:25:25 +0000474
Georg Brandl430e3622007-11-29 17:02:34 +0000475 print config.get('Section1', 'foo') # -> "Python is fun!"
476 config.remove_option('Section1', 'bar')
477 config.remove_option('Section1', 'baz')
478 print config.get('Section1', 'foo') # -> "Life is hard!"
479
480The function ``opt_move`` below can be used to move options between sections::
481
482 def opt_move(config, section1, section2, option):
483 try:
484 config.set(section2, option, config.get(section1, option, 1))
Georg Brandl392c6fc2008-05-25 07:25:25 +0000485 except ConfigParser.NoSectionError:
Georg Brandl430e3622007-11-29 17:02:34 +0000486 # Create non-existent section
487 config.add_section(section2)
488 opt_move(config, section1, section2, option)
Georg Brandl960b1862008-01-21 16:28:13 +0000489 else:
490 config.remove_option(section1, option)