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