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