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