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