blob: fe811debbd6b65a3797a959e5675b55b338f0ca2 [file] [log] [blame]
Alexandre Vassalottie2514c62008-05-14 22:44:22 +00001:mod:`configparser` --- Configuration file parser
Georg Brandl8ec7f652007-08-15 14:28:01 +00002=================================================
3
Georg Brandl0a11f962008-05-14 22:30:31 +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
Georg Brandl8ec7f652007-08-15 14:28:01 +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
24.. warning::
25
26 This library does *not* interpret or write the value-type prefixes used in the
27 Windows Registry extended version of INI syntax.
28
29The configuration file consists of sections, led by a ``[section]`` header and
30followed by ``name: value`` entries, with continuations in the style of
Georg Brandl27f43742008-03-26 09:32:46 +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 Brandl8ec7f652007-08-15 14:28:01 +000037
38For example::
39
40 [My Section]
41 foodir: %(dir)s/whatever
42 dir=frob
Georg Brandl27f43742008-03-26 09:32:46 +000043 long: this value continues
44 in the next line
Georg Brandl8ec7f652007-08-15 14:28:01 +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
53Sections are normally stored in a builtin dictionary. An alternative dictionary
54type 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
59.. class:: RawConfigParser([defaults[, dict_type]])
60
61 The basic configuration object. When *defaults* is given, it is initialized
62 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
63 be used to create the dictionary objects for the list of sections, for the
64 options within a section, and for the default values. This class does not
65 support the magical interpolation behavior.
66
67 .. versionadded:: 2.3
68
69 .. versionchanged:: 2.6
70 *dict_type* was added.
71
72
73.. class:: ConfigParser([defaults])
74
75 Derived class of :class:`RawConfigParser` that implements the magical
76 interpolation feature and adds optional arguments to the :meth:`get` and
77 :meth:`items` methods. The values in *defaults* must be appropriate for the
78 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
79 its value is the section name, and will override any value provided in
80 *defaults*.
81
82 All option names used in interpolation will be passed through the
83 :meth:`optionxform` method just like any other option name reference. For
84 example, using the default implementation of :meth:`optionxform` (which converts
85 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
86 equivalent.
87
88
89.. class:: SafeConfigParser([defaults])
90
91 Derived class of :class:`ConfigParser` that implements a more-sane variant of
92 the magical interpolation feature. This implementation is more predictable as
93 well. New applications should prefer this version if they don't need to be
94 compatible with older versions of Python.
95
Georg Brandlb19be572007-12-29 10:57:00 +000096 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl8ec7f652007-08-15 14:28:01 +000097
98 .. versionadded:: 2.3
99
100
101.. exception:: NoSectionError
102
103 Exception raised when a specified section is not found.
104
105
106.. exception:: DuplicateSectionError
107
108 Exception raised if :meth:`add_section` is called with the name of a section
109 that is already present.
110
111
112.. exception:: NoOptionError
113
114 Exception raised when a specified option is not found in the specified section.
115
116
117.. exception:: InterpolationError
118
119 Base class for exceptions raised when problems occur performing string
120 interpolation.
121
122
123.. exception:: InterpolationDepthError
124
125 Exception raised when string interpolation cannot be completed because the
126 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
127 :exc:`InterpolationError`.
128
129
130.. exception:: InterpolationMissingOptionError
131
132 Exception raised when an option referenced from a value does not exist. Subclass
133 of :exc:`InterpolationError`.
134
135 .. versionadded:: 2.3
136
137
138.. exception:: InterpolationSyntaxError
139
140 Exception raised when the source text into which substitutions are made does not
141 conform to the required syntax. Subclass of :exc:`InterpolationError`.
142
143 .. versionadded:: 2.3
144
145
146.. exception:: MissingSectionHeaderError
147
148 Exception raised when attempting to parse a file which has no section headers.
149
150
151.. exception:: ParsingError
152
153 Exception raised when errors occur attempting to parse a file.
154
155
156.. data:: MAX_INTERPOLATION_DEPTH
157
158 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
159 parameter is false. This is relevant only for the :class:`ConfigParser` class.
160
161
162.. seealso::
163
164 Module :mod:`shlex`
165 Support for a creating Unix shell-like mini-languages which can be used as an
166 alternate format for application configuration files.
167
168
169.. _rawconfigparser-objects:
170
171RawConfigParser Objects
172-----------------------
173
174:class:`RawConfigParser` instances have the following methods:
175
176
177.. method:: RawConfigParser.defaults()
178
179 Return a dictionary containing the instance-wide defaults.
180
181
182.. method:: RawConfigParser.sections()
183
184 Return a list of the sections available; ``DEFAULT`` is not included in the
185 list.
186
187
188.. method:: RawConfigParser.add_section(section)
189
190 Add a section named *section* to the instance. If a section by the given name
Facundo Batistab12f0b52008-02-23 12:46:10 +0000191 already exists, :exc:`DuplicateSectionError` is raised. If the name
192 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
193 :exc:`ValueError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
195.. method:: RawConfigParser.has_section(section)
196
197 Indicates whether the named section is present in the configuration. The
198 ``DEFAULT`` section is not acknowledged.
199
200
201.. method:: RawConfigParser.options(section)
202
203 Returns a list of options available in the specified *section*.
204
205
206.. method:: RawConfigParser.has_option(section, option)
207
208 If the given section exists, and contains the given option, return
209 :const:`True`; otherwise return :const:`False`.
210
211 .. versionadded:: 1.6
212
213
214.. method:: RawConfigParser.read(filenames)
215
216 Attempt to read and parse a list of filenames, returning a list of filenames
217 which were successfully parsed. If *filenames* is a string or Unicode string,
218 it is treated as a single filename. If a file named in *filenames* cannot be
219 opened, that file will be ignored. This is designed so that you can specify a
220 list of potential configuration file locations (for example, the current
221 directory, the user's home directory, and some system-wide directory), and all
222 existing configuration files in the list will be read. If none of the named
223 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
224 An application which requires initial values to be loaded from a file should
225 load the required file or files using :meth:`readfp` before calling :meth:`read`
226 for any optional files::
227
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000228 import configparser, os
Georg Brandl8ec7f652007-08-15 14:28:01 +0000229
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000230 config = configparser.ConfigParser()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000231 config.readfp(open('defaults.cfg'))
232 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
233
234 .. versionchanged:: 2.4
235 Returns list of successfully parsed filenames.
236
237
238.. method:: RawConfigParser.readfp(fp[, filename])
239
240 Read and parse configuration data from the file or file-like object in *fp*
241 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
242 has a :attr:`name` attribute, that is used for *filename*; the default is
243 ``<???>``.
244
245
246.. method:: RawConfigParser.get(section, option)
247
248 Get an *option* value for the named *section*.
249
250
251.. method:: RawConfigParser.getint(section, option)
252
253 A convenience method which coerces the *option* in the specified *section* to an
254 integer.
255
256
257.. method:: RawConfigParser.getfloat(section, option)
258
259 A convenience method which coerces the *option* in the specified *section* to a
260 floating point number.
261
262
263.. method:: RawConfigParser.getboolean(section, option)
264
265 A convenience method which coerces the *option* in the specified *section* to a
266 Boolean value. Note that the accepted values for the option are ``"1"``,
267 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
268 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
269 ``False``. These string values are checked in a case-insensitive manner. Any
270 other value will cause it to raise :exc:`ValueError`.
271
272
273.. method:: RawConfigParser.items(section)
274
275 Return a list of ``(name, value)`` pairs for each option in the given *section*.
276
277
278.. method:: RawConfigParser.set(section, option, value)
279
280 If the given section exists, set the given option to the specified value;
281 otherwise raise :exc:`NoSectionError`. While it is possible to use
282 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
283 true) for *internal* storage of non-string values, full functionality (including
284 interpolation and output to files) can only be achieved using string values.
285
286 .. versionadded:: 1.6
287
288
289.. method:: RawConfigParser.write(fileobject)
290
291 Write a representation of the configuration to the specified file object. This
292 representation can be parsed by a future :meth:`read` call.
293
294 .. versionadded:: 1.6
295
296
297.. method:: RawConfigParser.remove_option(section, option)
298
299 Remove the specified *option* from the specified *section*. If the section does
300 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
301 return :const:`True`; otherwise return :const:`False`.
302
303 .. versionadded:: 1.6
304
305
306.. method:: RawConfigParser.remove_section(section)
307
308 Remove the specified *section* from the configuration. If the section in fact
309 existed, return ``True``. Otherwise return ``False``.
310
311
312.. method:: RawConfigParser.optionxform(option)
313
314 Transforms the option name *option* as found in an input file or as passed in by
315 client code to the form that should be used in the internal structures. The
316 default implementation returns a lower-case version of *option*; subclasses may
317 override this or client code can set an attribute of this name on instances to
318 affect this behavior. Setting this to :func:`str`, for example, would make
319 option names case sensitive.
320
321
322.. _configparser-objects:
323
324ConfigParser Objects
325--------------------
326
327The :class:`ConfigParser` class extends some methods of the
328:class:`RawConfigParser` interface, adding some optional arguments.
329
330
331.. method:: ConfigParser.get(section, option[, raw[, vars]])
332
333 Get an *option* value for the named *section*. All the ``'%'`` interpolations
334 are expanded in the return values, based on the defaults passed into the
335 constructor, as well as the options *vars* provided, unless the *raw* argument
336 is true.
337
338
339.. method:: ConfigParser.items(section[, raw[, vars]])
340
341 Return a list of ``(name, value)`` pairs for each option in the given *section*.
342 Optional arguments have the same meaning as for the :meth:`get` method.
343
344 .. versionadded:: 2.3
345
346
347.. _safeconfigparser-objects:
348
349SafeConfigParser Objects
350------------------------
351
352The :class:`SafeConfigParser` class implements the same extended interface as
353:class:`ConfigParser`, with the following addition:
354
355
356.. method:: SafeConfigParser.set(section, option, value)
357
358 If the given section exists, set the given option to the specified value;
359 otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str`
360 or :class:`unicode`); if not, :exc:`TypeError` is raised.
361
362 .. versionadded:: 2.4
363
Georg Brandl430e3622007-11-29 17:02:34 +0000364
365Examples
366--------
367
368An example of writing to a configuration file::
369
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000370 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000371
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000372 config = configparser.RawConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000373
374 # When adding sections or items, add them in the reverse order of
375 # how you want them to be displayed in the actual file.
376 # In addition, please note that using RawConfigParser's and the raw
377 # mode of ConfigParser's respective set functions, you can assign
378 # non-string values to keys internally, but will receive an error
379 # when attempting to write to a file or when you get it in non-raw
380 # mode. SafeConfigParser does not allow such assignments to take place.
381 config.add_section('Section1')
382 config.set('Section1', 'int', '15')
383 config.set('Section1', 'bool', 'true')
384 config.set('Section1', 'float', '3.1415')
385 config.set('Section1', 'baz', 'fun')
386 config.set('Section1', 'bar', 'Python')
387 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
388
389 # Writing our configuration file to 'example.cfg'
390 with open('example.cfg', 'wb') as configfile:
391 config.write(configfile)
392
393An example of reading the configuration file again::
394
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000395 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000396
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000397 config = configparser.RawConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000398 config.read('example.cfg')
399
400 # getfloat() raises an exception if the value is not a float
401 # getint() and getboolean() also do this for their respective types
402 float = config.getfloat('Section1', 'float')
403 int = config.getint('Section1', 'int')
404 print float + int
405
406 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
407 # This is because we are using a RawConfigParser().
408 if config.getboolean('Section1', 'bool'):
409 print config.get('Section1', 'foo')
410
411To get interpolation, you will need to use a :class:`ConfigParser` or
412:class:`SafeConfigParser`::
413
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000414 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000415
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000416 config = configparser.ConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000417 config.read('example.cfg')
418
419 # Set the third, optional argument of get to 1 if you wish to use raw mode.
420 print config.get('Section1', 'foo', 0) # -> "Python is fun!"
421 print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
422
423 # The optional fourth argument is a dict with members that will take
424 # precedence in interpolation.
425 print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
426 'baz': 'evil'})
427
428Defaults are available in all three types of ConfigParsers. They are used in
429interpolation if an option used is not defined elsewhere. ::
430
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000431 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000432
433 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000434 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Georg Brandl430e3622007-11-29 17:02:34 +0000435 config.read('example.cfg')
436
437 print config.get('Section1', 'foo') # -> "Python is fun!"
438 config.remove_option('Section1', 'bar')
439 config.remove_option('Section1', 'baz')
440 print config.get('Section1', 'foo') # -> "Life is hard!"
441
442The function ``opt_move`` below can be used to move options between sections::
443
444 def opt_move(config, section1, section2, option):
445 try:
446 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000447 except configparser.NoSectionError:
Georg Brandl430e3622007-11-29 17:02:34 +0000448 # Create non-existent section
449 config.add_section(section2)
450 opt_move(config, section1, section2, option)
Georg Brandl960b1862008-01-21 16:28:13 +0000451 else:
452 config.remove_option(section1, option)