blob: aa4dc7cabfbfad6a62ec5fa31957c8b892710a92 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000066
67.. class:: ConfigParser([defaults])
68
69 Derived class of :class:`RawConfigParser` that implements the magical
70 interpolation feature and adds optional arguments to the :meth:`get` and
71 :meth:`items` methods. The values in *defaults* must be appropriate for the
72 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
73 its value is the section name, and will override any value provided in
74 *defaults*.
75
76 All option names used in interpolation will be passed through the
77 :meth:`optionxform` method just like any other option name reference. For
78 example, using the default implementation of :meth:`optionxform` (which converts
79 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
80 equivalent.
81
82
83.. class:: SafeConfigParser([defaults])
84
85 Derived class of :class:`ConfigParser` that implements a more-sane variant of
86 the magical interpolation feature. This implementation is more predictable as
87 well. New applications should prefer this version if they don't need to be
88 compatible with older versions of Python.
89
Christian Heimes5b5e81c2007-12-31 16:14:33 +000090 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl116aa622007-08-15 14:28:22 +000091
Georg Brandl116aa622007-08-15 14:28:22 +000092
93.. exception:: NoSectionError
94
95 Exception raised when a specified section is not found.
96
97
98.. exception:: DuplicateSectionError
99
100 Exception raised if :meth:`add_section` is called with the name of a section
101 that is already present.
102
103
104.. exception:: NoOptionError
105
106 Exception raised when a specified option is not found in the specified section.
107
108
109.. exception:: InterpolationError
110
111 Base class for exceptions raised when problems occur performing string
112 interpolation.
113
114
115.. exception:: InterpolationDepthError
116
117 Exception raised when string interpolation cannot be completed because the
118 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
119 :exc:`InterpolationError`.
120
121
122.. exception:: InterpolationMissingOptionError
123
124 Exception raised when an option referenced from a value does not exist. Subclass
125 of :exc:`InterpolationError`.
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128.. exception:: InterpolationSyntaxError
129
130 Exception raised when the source text into which substitutions are made does not
131 conform to the required syntax. Subclass of :exc:`InterpolationError`.
132
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134.. exception:: MissingSectionHeaderError
135
136 Exception raised when attempting to parse a file which has no section headers.
137
138
139.. exception:: ParsingError
140
141 Exception raised when errors occur attempting to parse a file.
142
143
144.. data:: MAX_INTERPOLATION_DEPTH
145
146 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
147 parameter is false. This is relevant only for the :class:`ConfigParser` class.
148
149
150.. seealso::
151
152 Module :mod:`shlex`
153 Support for a creating Unix shell-like mini-languages which can be used as an
154 alternate format for application configuration files.
155
156
157.. _rawconfigparser-objects:
158
159RawConfigParser Objects
160-----------------------
161
162:class:`RawConfigParser` instances have the following methods:
163
164
165.. method:: RawConfigParser.defaults()
166
167 Return a dictionary containing the instance-wide defaults.
168
169
170.. method:: RawConfigParser.sections()
171
172 Return a list of the sections available; ``DEFAULT`` is not included in the
173 list.
174
175
176.. method:: RawConfigParser.add_section(section)
177
178 Add a section named *section* to the instance. If a section by the given name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000179 already exists, :exc:`DuplicateSectionError` is raised. If the name
180 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
181 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183.. method:: RawConfigParser.has_section(section)
184
185 Indicates whether the named section is present in the configuration. The
186 ``DEFAULT`` section is not acknowledged.
187
188
189.. method:: RawConfigParser.options(section)
190
191 Returns a list of options available in the specified *section*.
192
193
194.. method:: RawConfigParser.has_option(section, option)
195
196 If the given section exists, and contains the given option, return
197 :const:`True`; otherwise return :const:`False`.
198
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200.. method:: RawConfigParser.read(filenames)
201
202 Attempt to read and parse a list of filenames, returning a list of filenames
Georg Brandlf6945182008-02-01 11:56:49 +0000203 which were successfully parsed. If *filenames* is a string,
Georg Brandl116aa622007-08-15 14:28:22 +0000204 it is treated as a single filename. If a file named in *filenames* cannot be
205 opened, that file will be ignored. This is designed so that you can specify a
206 list of potential configuration file locations (for example, the current
207 directory, the user's home directory, and some system-wide directory), and all
208 existing configuration files in the list will be read. If none of the named
209 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
210 An application which requires initial values to be loaded from a file should
211 load the required file or files using :meth:`readfp` before calling :meth:`read`
212 for any optional files::
213
214 import ConfigParser, os
215
216 config = ConfigParser.ConfigParser()
217 config.readfp(open('defaults.cfg'))
218 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
219
Georg Brandl116aa622007-08-15 14:28:22 +0000220
221.. method:: RawConfigParser.readfp(fp[, filename])
222
223 Read and parse configuration data from the file or file-like object in *fp*
224 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
225 has a :attr:`name` attribute, that is used for *filename*; the default is
226 ``<???>``.
227
228
229.. method:: RawConfigParser.get(section, option)
230
231 Get an *option* value for the named *section*.
232
233
234.. method:: RawConfigParser.getint(section, option)
235
236 A convenience method which coerces the *option* in the specified *section* to an
237 integer.
238
239
240.. method:: RawConfigParser.getfloat(section, option)
241
242 A convenience method which coerces the *option* in the specified *section* to a
243 floating point number.
244
245
246.. method:: RawConfigParser.getboolean(section, option)
247
248 A convenience method which coerces the *option* in the specified *section* to a
249 Boolean value. Note that the accepted values for the option are ``"1"``,
250 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
251 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
252 ``False``. These string values are checked in a case-insensitive manner. Any
253 other value will cause it to raise :exc:`ValueError`.
254
255
256.. method:: RawConfigParser.items(section)
257
258 Return a list of ``(name, value)`` pairs for each option in the given *section*.
259
260
261.. method:: RawConfigParser.set(section, option, value)
262
263 If the given section exists, set the given option to the specified value;
264 otherwise raise :exc:`NoSectionError`. While it is possible to use
265 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
266 true) for *internal* storage of non-string values, full functionality (including
267 interpolation and output to files) can only be achieved using string values.
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269
270.. method:: RawConfigParser.write(fileobject)
271
272 Write a representation of the configuration to the specified file object. This
273 representation can be parsed by a future :meth:`read` call.
274
Georg Brandl116aa622007-08-15 14:28:22 +0000275
276.. method:: RawConfigParser.remove_option(section, option)
277
278 Remove the specified *option* from the specified *section*. If the section does
279 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
280 return :const:`True`; otherwise return :const:`False`.
281
Georg Brandl116aa622007-08-15 14:28:22 +0000282
283.. method:: RawConfigParser.remove_section(section)
284
285 Remove the specified *section* from the configuration. If the section in fact
286 existed, return ``True``. Otherwise return ``False``.
287
288
289.. method:: RawConfigParser.optionxform(option)
290
291 Transforms the option name *option* as found in an input file or as passed in by
292 client code to the form that should be used in the internal structures. The
293 default implementation returns a lower-case version of *option*; subclasses may
294 override this or client code can set an attribute of this name on instances to
295 affect this behavior. Setting this to :func:`str`, for example, would make
296 option names case sensitive.
297
298
299.. _configparser-objects:
300
301ConfigParser Objects
302--------------------
303
304The :class:`ConfigParser` class extends some methods of the
305:class:`RawConfigParser` interface, adding some optional arguments.
306
307
308.. method:: ConfigParser.get(section, option[, raw[, vars]])
309
310 Get an *option* value for the named *section*. All the ``'%'`` interpolations
311 are expanded in the return values, based on the defaults passed into the
312 constructor, as well as the options *vars* provided, unless the *raw* argument
313 is true.
314
315
316.. method:: ConfigParser.items(section[, raw[, vars]])
317
318 Return a list of ``(name, value)`` pairs for each option in the given *section*.
319 Optional arguments have the same meaning as for the :meth:`get` method.
320
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322.. _safeconfigparser-objects:
323
324SafeConfigParser Objects
325------------------------
326
327The :class:`SafeConfigParser` class implements the same extended interface as
328:class:`ConfigParser`, with the following addition:
329
330
331.. method:: SafeConfigParser.set(section, option, value)
332
333 If the given section exists, set the given option to the specified value;
Georg Brandlf6945182008-02-01 11:56:49 +0000334 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
335 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000336
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000337
338Examples
339--------
340
341An example of writing to a configuration file::
342
343 import ConfigParser
344
345 config = ConfigParser.RawConfigParser()
346
347 # When adding sections or items, add them in the reverse order of
348 # how you want them to be displayed in the actual file.
349 # In addition, please note that using RawConfigParser's and the raw
350 # mode of ConfigParser's respective set functions, you can assign
351 # non-string values to keys internally, but will receive an error
352 # when attempting to write to a file or when you get it in non-raw
353 # mode. SafeConfigParser does not allow such assignments to take place.
354 config.add_section('Section1')
355 config.set('Section1', 'int', '15')
356 config.set('Section1', 'bool', 'true')
357 config.set('Section1', 'float', '3.1415')
358 config.set('Section1', 'baz', 'fun')
359 config.set('Section1', 'bar', 'Python')
360 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
361
362 # Writing our configuration file to 'example.cfg'
363 with open('example.cfg', 'wb') as configfile:
364 config.write(configfile)
365
366An example of reading the configuration file again::
367
368 import ConfigParser
369
370 config = ConfigParser.RawConfigParser()
371 config.read('example.cfg')
372
373 # getfloat() raises an exception if the value is not a float
374 # getint() and getboolean() also do this for their respective types
375 float = config.getfloat('Section1', 'float')
376 int = config.getint('Section1', 'int')
Georg Brandlf6945182008-02-01 11:56:49 +0000377 print(float + int)
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000378
379 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
380 # This is because we are using a RawConfigParser().
381 if config.getboolean('Section1', 'bool'):
Georg Brandlf6945182008-02-01 11:56:49 +0000382 print(config.get('Section1', 'foo'))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000383
384To get interpolation, you will need to use a :class:`ConfigParser` or
385:class:`SafeConfigParser`::
386
387 import ConfigParser
388
389 config = ConfigParser.ConfigParser()
390 config.read('example.cfg')
391
392 # Set the third, optional argument of get to 1 if you wish to use raw mode.
Georg Brandlf6945182008-02-01 11:56:49 +0000393 print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
394 print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000395
396 # The optional fourth argument is a dict with members that will take
397 # precedence in interpolation.
Georg Brandlf6945182008-02-01 11:56:49 +0000398 print(config.get('Section1', 'foo', 0, {'bar': 'Documentation',
399 'baz': 'evil'}))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000400
401Defaults are available in all three types of ConfigParsers. They are used in
402interpolation if an option used is not defined elsewhere. ::
403
404 import ConfigParser
405
406 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
407 config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
408 config.read('example.cfg')
409
Georg Brandlf6945182008-02-01 11:56:49 +0000410 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000411 config.remove_option('Section1', 'bar')
412 config.remove_option('Section1', 'baz')
Georg Brandlf6945182008-02-01 11:56:49 +0000413 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000414
415The function ``opt_move`` below can be used to move options between sections::
416
417 def opt_move(config, section1, section2, option):
418 try:
419 config.set(section2, option, config.get(section1, option, 1))
420 except ConfigParser.NoSectionError:
421 # Create non-existent section
422 config.add_section(section2)
423 opt_move(config, section1, section2, option)
Georg Brandl86def6c2008-01-21 20:36:10 +0000424 else:
425 config.remove_option(section1, option)