blob: 6a4e049f7652ba943b89fe3826694c95f2b56531 [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
Alexandre Vassalottic92fef92008-05-14 22:51:10 +00004.. module:: ConfigParser
5 :synopsis: Old name for the configparser module.
6
Georg Brandl0a11f962008-05-14 22:30:31 +00007.. module:: configparser
Georg Brandl8ec7f652007-08-15 14:28:01 +00008 :synopsis: Configuration file parser.
Alexandre Vassalottie2514c62008-05-14 22:44:22 +00009
Georg Brandl8ec7f652007-08-15 14:28:01 +000010.. moduleauthor:: Ken Manheimer <klm@zope.com>
11.. moduleauthor:: Barry Warsaw <bwarsaw@python.org>
12.. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
13.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>
14
Alexandre Vassalottic92fef92008-05-14 22:51:10 +000015.. note::
16 The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in
17 Python 3.0. It is importable under both names in Python 2.6 and the rest of
18 the 2.x series.
19
Georg Brandl8ec7f652007-08-15 14:28:01 +000020.. index::
21 pair: .ini; file
22 pair: configuration; file
23 single: ini file
24 single: Windows ini file
25
26This module defines the class :class:`ConfigParser`. The :class:`ConfigParser`
27class implements a basic configuration file parser language which provides a
28structure similar to what you would find on Microsoft Windows INI files. You
29can use this to write Python programs which can be customized by end users
30easily.
31
32.. warning::
33
34 This library does *not* interpret or write the value-type prefixes used in the
35 Windows Registry extended version of INI syntax.
36
37The configuration file consists of sections, led by a ``[section]`` header and
38followed by ``name: value`` entries, with continuations in the style of
Georg Brandl27f43742008-03-26 09:32:46 +000039:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
40accepted. Note that leading whitespace is removed from values. The optional
41values can contain format strings which refer to other values in the same
42section, or values in a special ``DEFAULT`` section. Additional defaults can be
43provided on initialization and retrieval. Lines beginning with ``'#'`` or
44``';'`` are ignored and may be used to provide comments.
Georg Brandl8ec7f652007-08-15 14:28:01 +000045
46For example::
47
48 [My Section]
49 foodir: %(dir)s/whatever
50 dir=frob
Georg Brandl27f43742008-03-26 09:32:46 +000051 long: this value continues
52 in the next line
Georg Brandl8ec7f652007-08-15 14:28:01 +000053
54would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
55All reference expansions are done on demand.
56
57Default values can be specified by passing them into the :class:`ConfigParser`
58constructor as a dictionary. Additional defaults may be passed into the
59:meth:`get` method which will override all others.
60
61Sections are normally stored in a builtin dictionary. An alternative dictionary
62type can be passed to the :class:`ConfigParser` constructor. For example, if a
63dictionary type is passed that sorts its keys, the sections will be sorted on
64write-back, as will be the keys within each section.
65
66
67.. class:: RawConfigParser([defaults[, dict_type]])
68
69 The basic configuration object. When *defaults* is given, it is initialized
70 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
71 be used to create the dictionary objects for the list of sections, for the
72 options within a section, and for the default values. This class does not
73 support the magical interpolation behavior.
74
75 .. versionadded:: 2.3
76
77 .. versionchanged:: 2.6
78 *dict_type* was added.
79
80
81.. class:: ConfigParser([defaults])
82
83 Derived class of :class:`RawConfigParser` that implements the magical
84 interpolation feature and adds optional arguments to the :meth:`get` and
85 :meth:`items` methods. The values in *defaults* must be appropriate for the
86 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
87 its value is the section name, and will override any value provided in
88 *defaults*.
89
90 All option names used in interpolation will be passed through the
91 :meth:`optionxform` method just like any other option name reference. For
92 example, using the default implementation of :meth:`optionxform` (which converts
93 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
94 equivalent.
95
96
97.. class:: SafeConfigParser([defaults])
98
99 Derived class of :class:`ConfigParser` that implements a more-sane variant of
100 the magical interpolation feature. This implementation is more predictable as
101 well. New applications should prefer this version if they don't need to be
102 compatible with older versions of Python.
103
Georg Brandlb19be572007-12-29 10:57:00 +0000104 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000105
106 .. versionadded:: 2.3
107
108
109.. exception:: NoSectionError
110
111 Exception raised when a specified section is not found.
112
113
114.. exception:: DuplicateSectionError
115
116 Exception raised if :meth:`add_section` is called with the name of a section
117 that is already present.
118
119
120.. exception:: NoOptionError
121
122 Exception raised when a specified option is not found in the specified section.
123
124
125.. exception:: InterpolationError
126
127 Base class for exceptions raised when problems occur performing string
128 interpolation.
129
130
131.. exception:: InterpolationDepthError
132
133 Exception raised when string interpolation cannot be completed because the
134 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
135 :exc:`InterpolationError`.
136
137
138.. exception:: InterpolationMissingOptionError
139
140 Exception raised when an option referenced from a value does not exist. Subclass
141 of :exc:`InterpolationError`.
142
143 .. versionadded:: 2.3
144
145
146.. exception:: InterpolationSyntaxError
147
148 Exception raised when the source text into which substitutions are made does not
149 conform to the required syntax. Subclass of :exc:`InterpolationError`.
150
151 .. versionadded:: 2.3
152
153
154.. exception:: MissingSectionHeaderError
155
156 Exception raised when attempting to parse a file which has no section headers.
157
158
159.. exception:: ParsingError
160
161 Exception raised when errors occur attempting to parse a file.
162
163
164.. data:: MAX_INTERPOLATION_DEPTH
165
166 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
167 parameter is false. This is relevant only for the :class:`ConfigParser` class.
168
169
170.. seealso::
171
172 Module :mod:`shlex`
173 Support for a creating Unix shell-like mini-languages which can be used as an
174 alternate format for application configuration files.
175
176
177.. _rawconfigparser-objects:
178
179RawConfigParser Objects
180-----------------------
181
182:class:`RawConfigParser` instances have the following methods:
183
184
185.. method:: RawConfigParser.defaults()
186
187 Return a dictionary containing the instance-wide defaults.
188
189
190.. method:: RawConfigParser.sections()
191
192 Return a list of the sections available; ``DEFAULT`` is not included in the
193 list.
194
195
196.. method:: RawConfigParser.add_section(section)
197
198 Add a section named *section* to the instance. If a section by the given name
Facundo Batistab12f0b52008-02-23 12:46:10 +0000199 already exists, :exc:`DuplicateSectionError` is raised. If the name
200 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
201 :exc:`ValueError` is raised.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202
203.. method:: RawConfigParser.has_section(section)
204
205 Indicates whether the named section is present in the configuration. The
206 ``DEFAULT`` section is not acknowledged.
207
208
209.. method:: RawConfigParser.options(section)
210
211 Returns a list of options available in the specified *section*.
212
213
214.. method:: RawConfigParser.has_option(section, option)
215
216 If the given section exists, and contains the given option, return
217 :const:`True`; otherwise return :const:`False`.
218
219 .. versionadded:: 1.6
220
221
222.. method:: RawConfigParser.read(filenames)
223
224 Attempt to read and parse a list of filenames, returning a list of filenames
225 which were successfully parsed. If *filenames* is a string or Unicode string,
226 it is treated as a single filename. If a file named in *filenames* cannot be
227 opened, that file will be ignored. This is designed so that you can specify a
228 list of potential configuration file locations (for example, the current
229 directory, the user's home directory, and some system-wide directory), and all
230 existing configuration files in the list will be read. If none of the named
231 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
232 An application which requires initial values to be loaded from a file should
233 load the required file or files using :meth:`readfp` before calling :meth:`read`
234 for any optional files::
235
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000236 import configparser, os
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000238 config = configparser.ConfigParser()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239 config.readfp(open('defaults.cfg'))
240 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
241
242 .. versionchanged:: 2.4
243 Returns list of successfully parsed filenames.
244
245
246.. method:: RawConfigParser.readfp(fp[, filename])
247
248 Read and parse configuration data from the file or file-like object in *fp*
249 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
250 has a :attr:`name` attribute, that is used for *filename*; the default is
251 ``<???>``.
252
253
254.. method:: RawConfigParser.get(section, option)
255
256 Get an *option* value for the named *section*.
257
258
259.. method:: RawConfigParser.getint(section, option)
260
261 A convenience method which coerces the *option* in the specified *section* to an
262 integer.
263
264
265.. method:: RawConfigParser.getfloat(section, option)
266
267 A convenience method which coerces the *option* in the specified *section* to a
268 floating point number.
269
270
271.. method:: RawConfigParser.getboolean(section, option)
272
273 A convenience method which coerces the *option* in the specified *section* to a
274 Boolean value. Note that the accepted values for the option are ``"1"``,
275 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
276 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
277 ``False``. These string values are checked in a case-insensitive manner. Any
278 other value will cause it to raise :exc:`ValueError`.
279
280
281.. method:: RawConfigParser.items(section)
282
283 Return a list of ``(name, value)`` pairs for each option in the given *section*.
284
285
286.. method:: RawConfigParser.set(section, option, value)
287
288 If the given section exists, set the given option to the specified value;
289 otherwise raise :exc:`NoSectionError`. While it is possible to use
290 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
291 true) for *internal* storage of non-string values, full functionality (including
292 interpolation and output to files) can only be achieved using string values.
293
294 .. versionadded:: 1.6
295
296
297.. method:: RawConfigParser.write(fileobject)
298
299 Write a representation of the configuration to the specified file object. This
300 representation can be parsed by a future :meth:`read` call.
301
302 .. versionadded:: 1.6
303
304
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
311 .. versionadded:: 1.6
312
313
314.. method:: RawConfigParser.remove_section(section)
315
316 Remove the specified *section* from the configuration. If the section in fact
317 existed, return ``True``. Otherwise return ``False``.
318
319
320.. method:: RawConfigParser.optionxform(option)
321
322 Transforms the option name *option* as found in an input file or as passed in by
323 client code to the form that should be used in the internal structures. The
324 default implementation returns a lower-case version of *option*; subclasses may
325 override this or client code can set an attribute of this name on instances to
326 affect this behavior. Setting this to :func:`str`, for example, would make
327 option names case sensitive.
328
329
330.. _configparser-objects:
331
332ConfigParser Objects
333--------------------
334
335The :class:`ConfigParser` class extends some methods of the
336:class:`RawConfigParser` interface, adding some optional arguments.
337
338
339.. method:: ConfigParser.get(section, option[, raw[, vars]])
340
341 Get an *option* value for the named *section*. All the ``'%'`` interpolations
342 are expanded in the return values, based on the defaults passed into the
343 constructor, as well as the options *vars* provided, unless the *raw* argument
344 is true.
345
346
347.. method:: ConfigParser.items(section[, raw[, vars]])
348
349 Return a list of ``(name, value)`` pairs for each option in the given *section*.
350 Optional arguments have the same meaning as for the :meth:`get` method.
351
352 .. versionadded:: 2.3
353
354
355.. _safeconfigparser-objects:
356
357SafeConfigParser Objects
358------------------------
359
360The :class:`SafeConfigParser` class implements the same extended interface as
361:class:`ConfigParser`, with the following addition:
362
363
364.. method:: SafeConfigParser.set(section, option, value)
365
366 If the given section exists, set the given option to the specified value;
367 otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str`
368 or :class:`unicode`); if not, :exc:`TypeError` is raised.
369
370 .. versionadded:: 2.4
371
Georg Brandl430e3622007-11-29 17:02:34 +0000372
373Examples
374--------
375
376An example of writing to a configuration file::
377
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000378 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000379
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000380 config = configparser.RawConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000381
382 # When adding sections or items, add them in the reverse order of
383 # how you want them to be displayed in the actual file.
384 # In addition, please note that using RawConfigParser's and the raw
385 # mode of ConfigParser's respective set functions, you can assign
386 # non-string values to keys internally, but will receive an error
387 # when attempting to write to a file or when you get it in non-raw
388 # mode. SafeConfigParser does not allow such assignments to take place.
389 config.add_section('Section1')
390 config.set('Section1', 'int', '15')
391 config.set('Section1', 'bool', 'true')
392 config.set('Section1', 'float', '3.1415')
393 config.set('Section1', 'baz', 'fun')
394 config.set('Section1', 'bar', 'Python')
395 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
396
397 # Writing our configuration file to 'example.cfg'
398 with open('example.cfg', 'wb') as configfile:
399 config.write(configfile)
400
401An example of reading the configuration file again::
402
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000403 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000404
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000405 config = configparser.RawConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000406 config.read('example.cfg')
407
408 # getfloat() raises an exception if the value is not a float
409 # getint() and getboolean() also do this for their respective types
410 float = config.getfloat('Section1', 'float')
411 int = config.getint('Section1', 'int')
412 print float + int
413
414 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
415 # This is because we are using a RawConfigParser().
416 if config.getboolean('Section1', 'bool'):
417 print config.get('Section1', 'foo')
418
419To get interpolation, you will need to use a :class:`ConfigParser` or
420:class:`SafeConfigParser`::
421
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000422 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000423
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000424 config = configparser.ConfigParser()
Georg Brandl430e3622007-11-29 17:02:34 +0000425 config.read('example.cfg')
426
427 # Set the third, optional argument of get to 1 if you wish to use raw mode.
428 print config.get('Section1', 'foo', 0) # -> "Python is fun!"
429 print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
430
431 # The optional fourth argument is a dict with members that will take
432 # precedence in interpolation.
433 print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
434 'baz': 'evil'})
435
436Defaults are available in all three types of ConfigParsers. They are used in
437interpolation if an option used is not defined elsewhere. ::
438
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000439 import configparser
Georg Brandl430e3622007-11-29 17:02:34 +0000440
441 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000442 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Georg Brandl430e3622007-11-29 17:02:34 +0000443 config.read('example.cfg')
444
445 print config.get('Section1', 'foo') # -> "Python is fun!"
446 config.remove_option('Section1', 'bar')
447 config.remove_option('Section1', 'baz')
448 print config.get('Section1', 'foo') # -> "Life is hard!"
449
450The function ``opt_move`` below can be used to move options between sections::
451
452 def opt_move(config, section1, section2, option):
453 try:
454 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalottie2514c62008-05-14 22:44:22 +0000455 except configparser.NoSectionError:
Georg Brandl430e3622007-11-29 17:02:34 +0000456 # Create non-existent section
457 config.add_section(section2)
458 opt_move(config, section1, section2, option)
Georg Brandl960b1862008-01-21 16:28:13 +0000459 else:
460 config.remove_option(section1, option)