blob: 1d097f942e90256eca64d6b137c5868ac181f122 [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
38For example::
39
40 [My Section]
41 foodir: %(dir)s/whatever
42 dir=frob
Christian Heimesf6cd9672008-03-26 13:45:42 +000043 long: this value continues
44 in the next line
Georg Brandl116aa622007-08-15 14:28:22 +000045
46would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
47All reference expansions are done on demand.
48
49Default values can be specified by passing them into the :class:`ConfigParser`
50constructor as a dictionary. Additional defaults may be passed into the
51:meth:`get` method which will override all others.
52
Georg Brandl22b34312009-07-26 14:54:51 +000053Sections are normally stored in a built-in dictionary. An alternative dictionary
Georg Brandl116aa622007-08-15 14:28:22 +000054type can be passed to the :class:`ConfigParser` constructor. For example, if a
55dictionary type is passed that sorts its keys, the sections will be sorted on
56write-back, as will be the keys within each section.
57
58
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000059.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +000060
61 The basic configuration object. When *defaults* is given, it is initialized
62 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
63 be used to create the dictionary objects for the list of sections, for the
64 options within a section, and for the default values. This class does not
65 support the magical interpolation behavior.
66
Raymond Hettinger231b7f12009-03-03 00:23:19 +000067 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000068 The default *dict_type* is :class:`collections.OrderedDict`.
69
Georg Brandl116aa622007-08-15 14:28:22 +000070
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000071.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 Derived class of :class:`RawConfigParser` that implements the magical
74 interpolation feature and adds optional arguments to the :meth:`get` and
75 :meth:`items` methods. The values in *defaults* must be appropriate for the
76 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
77 its value is the section name, and will override any value provided in
78 *defaults*.
79
80 All option names used in interpolation will be passed through the
81 :meth:`optionxform` method just like any other option name reference. For
82 example, using the default implementation of :meth:`optionxform` (which converts
83 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
84 equivalent.
85
Raymond Hettinger231b7f12009-03-03 00:23:19 +000086 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000087 The default *dict_type* is :class:`collections.OrderedDict`.
88
Georg Brandl116aa622007-08-15 14:28:22 +000089
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000090.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict)
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 Derived class of :class:`ConfigParser` that implements a more-sane variant of
93 the magical interpolation feature. This implementation is more predictable as
94 well. New applications should prefer this version if they don't need to be
95 compatible with older versions of Python.
96
Christian Heimes5b5e81c2007-12-31 16:14:33 +000097 .. XXX Need to explain what's safer/more predictable about it.
Georg Brandl116aa622007-08-15 14:28:22 +000098
Raymond Hettinger231b7f12009-03-03 00:23:19 +000099 .. versionchanged:: 3.1
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000100 The default *dict_type* is :class:`collections.OrderedDict`.
101
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103.. exception:: NoSectionError
104
105 Exception raised when a specified section is not found.
106
107
108.. exception:: DuplicateSectionError
109
110 Exception raised if :meth:`add_section` is called with the name of a section
111 that is already present.
112
113
114.. exception:: NoOptionError
115
116 Exception raised when a specified option is not found in the specified section.
117
118
119.. exception:: InterpolationError
120
121 Base class for exceptions raised when problems occur performing string
122 interpolation.
123
124
125.. exception:: InterpolationDepthError
126
127 Exception raised when string interpolation cannot be completed because the
128 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
129 :exc:`InterpolationError`.
130
131
132.. exception:: InterpolationMissingOptionError
133
134 Exception raised when an option referenced from a value does not exist. Subclass
135 of :exc:`InterpolationError`.
136
Georg Brandl116aa622007-08-15 14:28:22 +0000137
138.. exception:: InterpolationSyntaxError
139
140 Exception raised when the source text into which substitutions are made does not
141 conform to the required syntax. Subclass of :exc:`InterpolationError`.
142
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144.. exception:: MissingSectionHeaderError
145
146 Exception raised when attempting to parse a file which has no section headers.
147
148
149.. exception:: ParsingError
150
151 Exception raised when errors occur attempting to parse a file.
152
153
154.. data:: MAX_INTERPOLATION_DEPTH
155
156 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
157 parameter is false. This is relevant only for the :class:`ConfigParser` class.
158
159
160.. seealso::
161
162 Module :mod:`shlex`
163 Support for a creating Unix shell-like mini-languages which can be used as an
164 alternate format for application configuration files.
165
166
167.. _rawconfigparser-objects:
168
169RawConfigParser Objects
170-----------------------
171
172:class:`RawConfigParser` instances have the following methods:
173
174
175.. method:: RawConfigParser.defaults()
176
177 Return a dictionary containing the instance-wide defaults.
178
179
180.. method:: RawConfigParser.sections()
181
182 Return a list of the sections available; ``DEFAULT`` is not included in the
183 list.
184
185
186.. method:: RawConfigParser.add_section(section)
187
188 Add a section named *section* to the instance. If a section by the given name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000189 already exists, :exc:`DuplicateSectionError` is raised. If the name
190 ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
191 :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193.. method:: RawConfigParser.has_section(section)
194
195 Indicates whether the named section is present in the configuration. The
196 ``DEFAULT`` section is not acknowledged.
197
198
199.. method:: RawConfigParser.options(section)
200
201 Returns a list of options available in the specified *section*.
202
203
204.. method:: RawConfigParser.has_option(section, option)
205
206 If the given section exists, and contains the given option, return
207 :const:`True`; otherwise return :const:`False`.
208
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210.. method:: RawConfigParser.read(filenames)
211
212 Attempt to read and parse a list of filenames, returning a list of filenames
Georg Brandlf6945182008-02-01 11:56:49 +0000213 which were successfully parsed. If *filenames* is a string,
Georg Brandl116aa622007-08-15 14:28:22 +0000214 it is treated as a single filename. If a file named in *filenames* cannot be
215 opened, that file will be ignored. This is designed so that you can specify a
216 list of potential configuration file locations (for example, the current
217 directory, the user's home directory, and some system-wide directory), and all
218 existing configuration files in the list will be read. If none of the named
219 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
220 An application which requires initial values to be loaded from a file should
221 load the required file or files using :meth:`readfp` before calling :meth:`read`
222 for any optional files::
223
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000224 import configparser, os
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000226 config = configparser.ConfigParser()
Georg Brandl116aa622007-08-15 14:28:22 +0000227 config.readfp(open('defaults.cfg'))
228 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
229
Georg Brandl116aa622007-08-15 14:28:22 +0000230
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000231.. method:: RawConfigParser.readfp(fp, filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233 Read and parse configuration data from the file or file-like object in *fp*
Georg Brandl73753d32009-09-22 13:53:14 +0000234 (only the :meth:`readline` method is used). The file-like object must
235 operate in text mode, i.e. return strings from :meth:`readline`.
236
237 If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used
238 for *filename*; the default is ``<???>``.
Georg Brandl116aa622007-08-15 14:28:22 +0000239
240
241.. method:: RawConfigParser.get(section, option)
242
243 Get an *option* value for the named *section*.
244
245
246.. method:: RawConfigParser.getint(section, option)
247
248 A convenience method which coerces the *option* in the specified *section* to an
249 integer.
250
251
252.. method:: RawConfigParser.getfloat(section, option)
253
254 A convenience method which coerces the *option* in the specified *section* to a
255 floating point number.
256
257
258.. method:: RawConfigParser.getboolean(section, option)
259
260 A convenience method which coerces the *option* in the specified *section* to a
261 Boolean value. Note that the accepted values for the option are ``"1"``,
262 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
263 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
264 ``False``. These string values are checked in a case-insensitive manner. Any
265 other value will cause it to raise :exc:`ValueError`.
266
267
268.. method:: RawConfigParser.items(section)
269
270 Return a list of ``(name, value)`` pairs for each option in the given *section*.
271
272
273.. method:: RawConfigParser.set(section, option, value)
274
275 If the given section exists, set the given option to the specified value;
276 otherwise raise :exc:`NoSectionError`. While it is possible to use
277 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
278 true) for *internal* storage of non-string values, full functionality (including
279 interpolation and output to files) can only be achieved using string values.
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282.. method:: RawConfigParser.write(fileobject)
283
Georg Brandl73753d32009-09-22 13:53:14 +0000284 Write a representation of the configuration to the specified file object,
285 which must be opened in text mode (accepting strings). This representation
286 can be parsed by a future :meth:`read` call.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289.. method:: RawConfigParser.remove_option(section, option)
290
291 Remove the specified *option* from the specified *section*. If the section does
292 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
293 return :const:`True`; otherwise return :const:`False`.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296.. method:: RawConfigParser.remove_section(section)
297
298 Remove the specified *section* from the configuration. If the section in fact
299 existed, return ``True``. Otherwise return ``False``.
300
301
302.. method:: RawConfigParser.optionxform(option)
303
Georg Brandl495f7b52009-10-27 15:28:25 +0000304 Transforms the option name *option* as found in an input file or as passed in
305 by client code to the form that should be used in the internal structures.
306 The default implementation returns a lower-case version of *option*;
307 subclasses may override this or client code can set an attribute of this name
308 on instances to affect this behavior.
309
310 You don't necessarily need to subclass a ConfigParser to use this method, you
311 can also re-set it on an instance, to a function that takes a string
312 argument. Setting it to ``str``, for example, would make option names case
313 sensitive::
314
315 cfgparser = ConfigParser()
316 ...
317 cfgparser.optionxform = str
318
319 Note that when reading configuration files, whitespace around the
320 option names are stripped before :meth:`optionxform` is called.
Georg Brandl116aa622007-08-15 14:28:22 +0000321
322
323.. _configparser-objects:
324
325ConfigParser Objects
326--------------------
327
328The :class:`ConfigParser` class extends some methods of the
329:class:`RawConfigParser` interface, adding some optional arguments.
330
331
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000332.. method:: ConfigParser.get(section, option, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334 Get an *option* value for the named *section*. All the ``'%'`` interpolations
335 are expanded in the return values, based on the defaults passed into the
336 constructor, as well as the options *vars* provided, unless the *raw* argument
337 is true.
338
339
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000340.. method:: ConfigParser.items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000341
342 Return a list of ``(name, value)`` pairs for each option in the given *section*.
343 Optional arguments have the same meaning as for the :meth:`get` method.
344
Georg Brandl116aa622007-08-15 14:28:22 +0000345
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;
Georg Brandlf6945182008-02-01 11:56:49 +0000358 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
359 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000361
362Examples
363--------
364
365An example of writing to a configuration file::
366
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000367 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000368
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000369 config = configparser.RawConfigParser()
Georg Brandl48310cd2009-01-03 21:18:54 +0000370
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000371 # When adding sections or items, add them in the reverse order of
372 # how you want them to be displayed in the actual file.
373 # In addition, please note that using RawConfigParser's and the raw
374 # mode of ConfigParser's respective set functions, you can assign
375 # non-string values to keys internally, but will receive an error
376 # when attempting to write to a file or when you get it in non-raw
377 # mode. SafeConfigParser does not allow such assignments to take place.
378 config.add_section('Section1')
379 config.set('Section1', 'int', '15')
380 config.set('Section1', 'bool', 'true')
381 config.set('Section1', 'float', '3.1415')
382 config.set('Section1', 'baz', 'fun')
383 config.set('Section1', 'bar', 'Python')
384 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl48310cd2009-01-03 21:18:54 +0000385
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000386 # Writing our configuration file to 'example.cfg'
Georg Brandl73753d32009-09-22 13:53:14 +0000387 with open('example.cfg', 'w') as configfile:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000388 config.write(configfile)
389
390An example of reading the configuration file again::
391
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000392 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000393
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000394 config = configparser.RawConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000395 config.read('example.cfg')
396
397 # getfloat() raises an exception if the value is not a float
398 # getint() and getboolean() also do this for their respective types
399 float = config.getfloat('Section1', 'float')
400 int = config.getint('Section1', 'int')
Georg Brandlf6945182008-02-01 11:56:49 +0000401 print(float + int)
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000402
403 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
404 # This is because we are using a RawConfigParser().
405 if config.getboolean('Section1', 'bool'):
Georg Brandlf6945182008-02-01 11:56:49 +0000406 print(config.get('Section1', 'foo'))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000407
408To get interpolation, you will need to use a :class:`ConfigParser` or
409:class:`SafeConfigParser`::
410
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000411 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000412
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000413 config = configparser.ConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000414 config.read('example.cfg')
415
416 # Set the third, optional argument of get to 1 if you wish to use raw mode.
Georg Brandlf6945182008-02-01 11:56:49 +0000417 print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
418 print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000419
420 # The optional fourth argument is a dict with members that will take
421 # precedence in interpolation.
Georg Brandlf6945182008-02-01 11:56:49 +0000422 print(config.get('Section1', 'foo', 0, {'bar': 'Documentation',
423 'baz': 'evil'}))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000424
Georg Brandl48310cd2009-01-03 21:18:54 +0000425Defaults are available in all three types of ConfigParsers. They are used in
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000426interpolation if an option used is not defined elsewhere. ::
427
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000428 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000429
430 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000431 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000432 config.read('example.cfg')
Georg Brandl48310cd2009-01-03 21:18:54 +0000433
Georg Brandlf6945182008-02-01 11:56:49 +0000434 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000435 config.remove_option('Section1', 'bar')
436 config.remove_option('Section1', 'baz')
Georg Brandlf6945182008-02-01 11:56:49 +0000437 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000438
439The function ``opt_move`` below can be used to move options between sections::
440
441 def opt_move(config, section1, section2, option):
442 try:
443 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000444 except configparser.NoSectionError:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000445 # Create non-existent section
446 config.add_section(section2)
447 opt_move(config, section1, section2, option)
Georg Brandl86def6c2008-01-21 20:36:10 +0000448 else:
449 config.remove_option(section1, option)