blob: 1afdf502afbd58da6cbcd4cfe70206240bc0eda0 [file] [log] [blame]
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00001:mod:`configparser` --- Configuration file parser
Georg Brandl116aa622007-08-15 14:28:22 +00002=================================================
3
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00004.. module:: configparser
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Configuration file parser.
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +00006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. 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
Georg Brandl116aa622007-08-15 14:28:22 +000012.. index::
13 pair: .ini; file
14 pair: configuration; file
15 single: ini file
16 single: Windows ini file
17
18This module defines the class :class:`ConfigParser`. The :class:`ConfigParser`
19class implements a basic configuration file parser language which provides a
20structure similar to what you would find on Microsoft Windows INI files. You
21can use this to write Python programs which can be customized by end users
22easily.
23
Georg Brandle720c0a2009-04-27 16:20:50 +000024.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000025
Georg Brandle720c0a2009-04-27 16:20:50 +000026 This library does *not* interpret or write the value-type prefixes used in
27 the Windows Registry extended version of INI syntax.
Georg Brandl116aa622007-08-15 14:28:22 +000028
29The configuration file consists of sections, led by a ``[section]`` header and
30followed by ``name: value`` entries, with continuations in the style of
Christian Heimesf6cd9672008-03-26 13:45:42 +000031:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
32accepted. Note that leading whitespace is removed from values. The optional
33values can contain format strings which refer to other values in the same
34section, or values in a special ``DEFAULT`` section. Additional defaults can be
35provided on initialization and retrieval. Lines beginning with ``'#'`` or
36``';'`` are ignored and may be used to provide comments.
Georg Brandl116aa622007-08-15 14:28:22 +000037
Georg Brandl1fa11af2010-08-01 21:03:01 +000038Configuration files may include comments, prefixed by specific characters (``#``
39and ``;``). Comments may appear on their own in an otherwise empty line, or may
40be entered in lines holding values or spection names. In the latter case, they
41need to be preceded by a whitespace character to be recognized as a comment.
42(For backwards compatibility, only ``;`` starts an inline comment, while ``#``
43does not.)
44
45On top of the core functionality, :class:`SafeConfigParser` supports
46interpolation. This means values can contain format strings which refer to
47other values in the same section, or values in a special ``DEFAULT`` section.
48Additional defaults can be provided on initialization.
49
Georg Brandl116aa622007-08-15 14:28:22 +000050For example::
51
52 [My Section]
53 foodir: %(dir)s/whatever
54 dir=frob
Christian Heimesf6cd9672008-03-26 13:45:42 +000055 long: this value continues
56 in the next line
Georg Brandl116aa622007-08-15 14:28:22 +000057
58would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
59All reference expansions are done on demand.
60
61Default values can be specified by passing them into the :class:`ConfigParser`
62constructor as a dictionary. Additional defaults may be passed into the
63:meth:`get` method which will override all others.
64
Georg Brandlc5605df2009-08-13 08:26:44 +000065Sections are normally stored in a built-in dictionary. An alternative dictionary
Georg Brandl116aa622007-08-15 14:28:22 +000066type can be passed to the :class:`ConfigParser` constructor. For example, if a
67dictionary type is passed that sorts its keys, the sections will be sorted on
68write-back, as will be the keys within each section.
69
70
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000071.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 The basic configuration object. When *defaults* is given, it is initialized
74 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
75 be used to create the dictionary objects for the list of sections, for the
76 options within a section, and for the default values. This class does not
77 support the magical interpolation behavior.
78
Raymond Hettinger231b7f12009-03-03 00:23:19 +000079 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000080 The default *dict_type* is :class:`collections.OrderedDict`.
81
Georg Brandl116aa622007-08-15 14:28:22 +000082
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000083.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +000084
85 Derived class of :class:`RawConfigParser` that implements the magical
86 interpolation feature and adds optional arguments to the :meth:`get` and
87 :meth:`items` methods. The values in *defaults* must be appropriate for the
88 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
89 its value is the section name, and will override any value provided in
90 *defaults*.
91
92 All option names used in interpolation will be passed through the
93 :meth:`optionxform` method just like any other option name reference. For
94 example, using the default implementation of :meth:`optionxform` (which converts
95 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
96 equivalent.
97
Raymond Hettinger231b7f12009-03-03 00:23:19 +000098 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000099 The default *dict_type* is :class:`collections.OrderedDict`.
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000102.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104 Derived class of :class:`ConfigParser` that implements a more-sane variant of
105 the magical interpolation feature. This implementation is more predictable as
106 well. New applications should prefer this version if they don't need to be
107 compatible with older versions of Python.
108
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000109 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl116aa622007-08-15 14:28:22 +0000110
Raymond Hettinger231b7f12009-03-03 00:23:19 +0000111 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000112 The default *dict_type* is :class:`collections.OrderedDict`.
113
Georg Brandl116aa622007-08-15 14:28:22 +0000114
Georg Brandl1fa11af2010-08-01 21:03:01 +0000115.. exception:: Error
116
117 Base class for all other configparser exceptions.
118
119
Georg Brandl116aa622007-08-15 14:28:22 +0000120.. exception:: NoSectionError
121
122 Exception raised when a specified section is not found.
123
124
125.. exception:: DuplicateSectionError
126
127 Exception raised if :meth:`add_section` is called with the name of a section
128 that is already present.
129
130
131.. exception:: NoOptionError
132
133 Exception raised when a specified option is not found in the specified section.
134
135
136.. exception:: InterpolationError
137
138 Base class for exceptions raised when problems occur performing string
139 interpolation.
140
141
142.. exception:: InterpolationDepthError
143
144 Exception raised when string interpolation cannot be completed because the
145 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
146 :exc:`InterpolationError`.
147
148
149.. exception:: InterpolationMissingOptionError
150
151 Exception raised when an option referenced from a value does not exist. Subclass
152 of :exc:`InterpolationError`.
153
Georg Brandl116aa622007-08-15 14:28:22 +0000154
155.. exception:: InterpolationSyntaxError
156
157 Exception raised when the source text into which substitutions are made does not
158 conform to the required syntax. Subclass of :exc:`InterpolationError`.
159
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161.. exception:: MissingSectionHeaderError
162
163 Exception raised when attempting to parse a file which has no section headers.
164
165
166.. exception:: ParsingError
167
168 Exception raised when errors occur attempting to parse a file.
169
170
171.. data:: MAX_INTERPOLATION_DEPTH
172
173 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
174 parameter is false. This is relevant only for the :class:`ConfigParser` class.
175
176
177.. seealso::
178
179 Module :mod:`shlex`
180 Support for a creating Unix shell-like mini-languages which can be used as an
181 alternate format for application configuration files.
182
183
184.. _rawconfigparser-objects:
185
186RawConfigParser Objects
187-----------------------
188
189:class:`RawConfigParser` instances have the following methods:
190
191
192.. method:: RawConfigParser.defaults()
193
194 Return a dictionary containing the instance-wide defaults.
195
196
197.. method:: RawConfigParser.sections()
198
199 Return a list of the sections available; ``DEFAULT`` is not included in the
200 list.
201
202
203.. method:: RawConfigParser.add_section(section)
204
205 Add a section named *section* to the instance. If a section by the given name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000206 already exists, :exc:`DuplicateSectionError` is raised. If the name
207 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
208 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210.. method:: RawConfigParser.has_section(section)
211
212 Indicates whether the named section is present in the configuration. The
213 ``DEFAULT`` section is not acknowledged.
214
215
216.. method:: RawConfigParser.options(section)
217
218 Returns a list of options available in the specified *section*.
219
220
221.. method:: RawConfigParser.has_option(section, option)
222
223 If the given section exists, and contains the given option, return
224 :const:`True`; otherwise return :const:`False`.
225
Georg Brandl116aa622007-08-15 14:28:22 +0000226
227.. method:: RawConfigParser.read(filenames)
228
229 Attempt to read and parse a list of filenames, returning a list of filenames
Georg Brandlf6945182008-02-01 11:56:49 +0000230 which were successfully parsed. If *filenames* is a string,
Georg Brandl116aa622007-08-15 14:28:22 +0000231 it is treated as a single filename. If a file named in *filenames* cannot be
232 opened, that file will be ignored. This is designed so that you can specify a
233 list of potential configuration file locations (for example, the current
234 directory, the user's home directory, and some system-wide directory), and all
235 existing configuration files in the list will be read. If none of the named
236 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
237 An application which requires initial values to be loaded from a file should
238 load the required file or files using :meth:`readfp` before calling :meth:`read`
239 for any optional files::
240
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000241 import configparser, os
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000243 config = configparser.ConfigParser()
Georg Brandl116aa622007-08-15 14:28:22 +0000244 config.readfp(open('defaults.cfg'))
245 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000248.. method:: RawConfigParser.readfp(fp, filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250 Read and parse configuration data from the file or file-like object in *fp*
Georg Brandl22fff432009-10-27 20:19:02 +0000251 (only the :meth:`readline` method is used). The file-like object must
252 operate in text mode, i.e. return strings from :meth:`readline`.
253
254 If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used
255 for *filename*; the default is ``<???>``.
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257
258.. method:: RawConfigParser.get(section, option)
259
260 Get an *option* value for the named *section*.
261
262
263.. method:: RawConfigParser.getint(section, option)
264
265 A convenience method which coerces the *option* in the specified *section* to an
266 integer.
267
268
269.. method:: RawConfigParser.getfloat(section, option)
270
271 A convenience method which coerces the *option* in the specified *section* to a
272 floating point number.
273
274
275.. method:: RawConfigParser.getboolean(section, option)
276
277 A convenience method which coerces the *option* in the specified *section* to a
278 Boolean value. Note that the accepted values for the option are ``"1"``,
279 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
280 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
281 ``False``. These string values are checked in a case-insensitive manner. Any
282 other value will cause it to raise :exc:`ValueError`.
283
284
285.. method:: RawConfigParser.items(section)
286
287 Return a list of ``(name, value)`` pairs for each option in the given *section*.
288
289
290.. method:: RawConfigParser.set(section, option, value)
291
292 If the given section exists, set the given option to the specified value;
293 otherwise raise :exc:`NoSectionError`. While it is possible to use
294 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
295 true) for *internal* storage of non-string values, full functionality (including
296 interpolation and output to files) can only be achieved using string values.
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299.. method:: RawConfigParser.write(fileobject)
300
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000301 Write a representation of the configuration to the specified :term:`file object`,
Georg Brandl22fff432009-10-27 20:19:02 +0000302 which must be opened in text mode (accepting strings). This representation
303 can be parsed by a future :meth:`read` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
Georg Brandl116aa622007-08-15 14:28:22 +0000305
306.. method:: RawConfigParser.remove_option(section, option)
307
308 Remove the specified *option* from the specified *section*. If the section does
309 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
310 return :const:`True`; otherwise return :const:`False`.
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
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
Georg Brandl628e6f92009-10-27 20:24:45 +0000321 Transforms the option name *option* as found in an input file or as passed in
322 by client code to the form that should be used in the internal structures.
323 The default implementation returns a lower-case version of *option*;
324 subclasses may override this or client code can set an attribute of this name
325 on instances to affect this behavior.
326
327 You don't necessarily need to subclass a ConfigParser to use this method, you
328 can also re-set it on an instance, to a function that takes a string
329 argument. Setting it to ``str``, for example, would make option names case
330 sensitive::
331
332 cfgparser = ConfigParser()
333 ...
334 cfgparser.optionxform = str
335
336 Note that when reading configuration files, whitespace around the
337 option names are stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339
340.. _configparser-objects:
341
342ConfigParser Objects
343--------------------
344
345The :class:`ConfigParser` class extends some methods of the
346:class:`RawConfigParser` interface, adding some optional arguments.
347
348
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000349.. method:: ConfigParser.get(section, option, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000350
Georg Brandl1fa11af2010-08-01 21:03:01 +0000351 Get an *option* value for the named *section*. If *vars* is provided, it
352 must be a dictionary. The *option* is looked up in *vars* (if provided),
353 *section*, and in *defaults* in that order.
354
355 All the ``'%'`` interpolations are expanded in the return values, unless the
356 *raw* argument is true. Values for interpolation keys are looked up in the
357 same manner as the option.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000360.. method:: ConfigParser.items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000361
362 Return a list of ``(name, value)`` pairs for each option in the given *section*.
363 Optional arguments have the same meaning as for the :meth:`get` method.
364
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366.. _safeconfigparser-objects:
367
368SafeConfigParser Objects
369------------------------
370
371The :class:`SafeConfigParser` class implements the same extended interface as
372:class:`ConfigParser`, with the following addition:
373
374
375.. method:: SafeConfigParser.set(section, option, value)
376
377 If the given section exists, set the given option to the specified value;
Georg Brandlf6945182008-02-01 11:56:49 +0000378 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
379 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000381
382Examples
383--------
384
385An example of writing to a configuration file::
386
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000387 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000388
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000389 config = configparser.RawConfigParser()
Georg Brandl48310cd2009-01-03 21:18:54 +0000390
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000391 # When adding sections or items, add them in the reverse order of
392 # how you want them to be displayed in the actual file.
393 # In addition, please note that using RawConfigParser's and the raw
394 # mode of ConfigParser's respective set functions, you can assign
395 # non-string values to keys internally, but will receive an error
396 # when attempting to write to a file or when you get it in non-raw
397 # mode. SafeConfigParser does not allow such assignments to take place.
398 config.add_section('Section1')
399 config.set('Section1', 'int', '15')
400 config.set('Section1', 'bool', 'true')
401 config.set('Section1', 'float', '3.1415')
402 config.set('Section1', 'baz', 'fun')
403 config.set('Section1', 'bar', 'Python')
404 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl48310cd2009-01-03 21:18:54 +0000405
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000406 # Writing our configuration file to 'example.cfg'
Georg Brandl22fff432009-10-27 20:19:02 +0000407 with open('example.cfg', 'w') as configfile:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000408 config.write(configfile)
409
410An example of reading the configuration file again::
411
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000412 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000413
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000414 config = configparser.RawConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000415 config.read('example.cfg')
416
417 # getfloat() raises an exception if the value is not a float
418 # getint() and getboolean() also do this for their respective types
419 float = config.getfloat('Section1', 'float')
420 int = config.getint('Section1', 'int')
Georg Brandlf6945182008-02-01 11:56:49 +0000421 print(float + int)
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000422
423 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
424 # This is because we are using a RawConfigParser().
425 if config.getboolean('Section1', 'bool'):
Georg Brandlf6945182008-02-01 11:56:49 +0000426 print(config.get('Section1', 'foo'))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000427
428To get interpolation, you will need to use a :class:`ConfigParser` or
429:class:`SafeConfigParser`::
430
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000431 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000432
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000433 config = configparser.ConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000434 config.read('example.cfg')
435
436 # Set the third, optional argument of get to 1 if you wish to use raw mode.
Georg Brandlf6945182008-02-01 11:56:49 +0000437 print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
438 print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000439
440 # The optional fourth argument is a dict with members that will take
441 # precedence in interpolation.
Georg Brandlf6945182008-02-01 11:56:49 +0000442 print(config.get('Section1', 'foo', 0, {'bar': 'Documentation',
443 'baz': 'evil'}))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000444
Georg Brandl48310cd2009-01-03 21:18:54 +0000445Defaults are available in all three types of ConfigParsers. They are used in
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000446interpolation if an option used is not defined elsewhere. ::
447
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000448 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000449
450 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000451 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000452 config.read('example.cfg')
Georg Brandl48310cd2009-01-03 21:18:54 +0000453
Georg Brandlf6945182008-02-01 11:56:49 +0000454 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000455 config.remove_option('Section1', 'bar')
456 config.remove_option('Section1', 'baz')
Georg Brandlf6945182008-02-01 11:56:49 +0000457 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000458
459The function ``opt_move`` below can be used to move options between sections::
460
461 def opt_move(config, section1, section2, option):
462 try:
463 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000464 except configparser.NoSectionError:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000465 # Create non-existent section
466 config.add_section(section2)
467 opt_move(config, section1, section2, option)
Georg Brandl86def6c2008-01-21 20:36:10 +0000468 else:
469 config.remove_option(section1, option)