blob: 6f840b9552232464c5224052689085e3ca7fe3b3 [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
53Sections are normally stored in a builtin dictionary. An alternative dictionary
54type 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*
234 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
235 has a :attr:`name` attribute, that is used for *filename*; the default is
236 ``<???>``.
237
238
239.. method:: RawConfigParser.get(section, option)
240
241 Get an *option* value for the named *section*.
242
243
244.. method:: RawConfigParser.getint(section, option)
245
246 A convenience method which coerces the *option* in the specified *section* to an
247 integer.
248
249
250.. method:: RawConfigParser.getfloat(section, option)
251
252 A convenience method which coerces the *option* in the specified *section* to a
253 floating point number.
254
255
256.. method:: RawConfigParser.getboolean(section, option)
257
258 A convenience method which coerces the *option* in the specified *section* to a
259 Boolean value. Note that the accepted values for the option are ``"1"``,
260 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
261 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
262 ``False``. These string values are checked in a case-insensitive manner. Any
263 other value will cause it to raise :exc:`ValueError`.
264
265
266.. method:: RawConfigParser.items(section)
267
268 Return a list of ``(name, value)`` pairs for each option in the given *section*.
269
270
271.. method:: RawConfigParser.set(section, option, value)
272
273 If the given section exists, set the given option to the specified value;
274 otherwise raise :exc:`NoSectionError`. While it is possible to use
275 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
276 true) for *internal* storage of non-string values, full functionality (including
277 interpolation and output to files) can only be achieved using string values.
278
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280.. method:: RawConfigParser.write(fileobject)
281
282 Write a representation of the configuration to the specified file object. This
283 representation can be parsed by a future :meth:`read` call.
284
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286.. method:: RawConfigParser.remove_option(section, option)
287
288 Remove the specified *option* from the specified *section*. If the section does
289 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
290 return :const:`True`; otherwise return :const:`False`.
291
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293.. method:: RawConfigParser.remove_section(section)
294
295 Remove the specified *section* from the configuration. If the section in fact
296 existed, return ``True``. Otherwise return ``False``.
297
298
299.. method:: RawConfigParser.optionxform(option)
300
301 Transforms the option name *option* as found in an input file or as passed in by
302 client code to the form that should be used in the internal structures. The
303 default implementation returns a lower-case version of *option*; subclasses may
304 override this or client code can set an attribute of this name on instances to
305 affect this behavior. Setting this to :func:`str`, for example, would make
306 option names case sensitive.
307
308
309.. _configparser-objects:
310
311ConfigParser Objects
312--------------------
313
314The :class:`ConfigParser` class extends some methods of the
315:class:`RawConfigParser` interface, adding some optional arguments.
316
317
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000318.. method:: ConfigParser.get(section, option, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320 Get an *option* value for the named *section*. All the ``'%'`` interpolations
321 are expanded in the return values, based on the defaults passed into the
322 constructor, as well as the options *vars* provided, unless the *raw* argument
323 is true.
324
325
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000326.. method:: ConfigParser.items(section, raw=False, vars=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000327
328 Return a list of ``(name, value)`` pairs for each option in the given *section*.
329 Optional arguments have the same meaning as for the :meth:`get` method.
330
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332.. _safeconfigparser-objects:
333
334SafeConfigParser Objects
335------------------------
336
337The :class:`SafeConfigParser` class implements the same extended interface as
338:class:`ConfigParser`, with the following addition:
339
340
341.. method:: SafeConfigParser.set(section, option, value)
342
343 If the given section exists, set the given option to the specified value;
Georg Brandlf6945182008-02-01 11:56:49 +0000344 otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is
345 not, :exc:`TypeError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000347
348Examples
349--------
350
351An example of writing to a configuration file::
352
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000353 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000354
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000355 config = configparser.RawConfigParser()
Georg Brandl48310cd2009-01-03 21:18:54 +0000356
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000357 # When adding sections or items, add them in the reverse order of
358 # how you want them to be displayed in the actual file.
359 # In addition, please note that using RawConfigParser's and the raw
360 # mode of ConfigParser's respective set functions, you can assign
361 # non-string values to keys internally, but will receive an error
362 # when attempting to write to a file or when you get it in non-raw
363 # mode. SafeConfigParser does not allow such assignments to take place.
364 config.add_section('Section1')
365 config.set('Section1', 'int', '15')
366 config.set('Section1', 'bool', 'true')
367 config.set('Section1', 'float', '3.1415')
368 config.set('Section1', 'baz', 'fun')
369 config.set('Section1', 'bar', 'Python')
370 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
Georg Brandl48310cd2009-01-03 21:18:54 +0000371
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000372 # Writing our configuration file to 'example.cfg'
373 with open('example.cfg', 'wb') as configfile:
374 config.write(configfile)
375
376An example of reading the configuration file again::
377
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000378 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000379
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000380 config = configparser.RawConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000381 config.read('example.cfg')
382
383 # getfloat() raises an exception if the value is not a float
384 # getint() and getboolean() also do this for their respective types
385 float = config.getfloat('Section1', 'float')
386 int = config.getint('Section1', 'int')
Georg Brandlf6945182008-02-01 11:56:49 +0000387 print(float + int)
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000388
389 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
390 # This is because we are using a RawConfigParser().
391 if config.getboolean('Section1', 'bool'):
Georg Brandlf6945182008-02-01 11:56:49 +0000392 print(config.get('Section1', 'foo'))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000393
394To get interpolation, you will need to use a :class:`ConfigParser` or
395:class:`SafeConfigParser`::
396
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000397 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000398
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000399 config = configparser.ConfigParser()
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000400 config.read('example.cfg')
401
402 # Set the third, optional argument of get to 1 if you wish to use raw mode.
Georg Brandlf6945182008-02-01 11:56:49 +0000403 print(config.get('Section1', 'foo', 0)) # -> "Python is fun!"
404 print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000405
406 # The optional fourth argument is a dict with members that will take
407 # precedence in interpolation.
Georg Brandlf6945182008-02-01 11:56:49 +0000408 print(config.get('Section1', 'foo', 0, {'bar': 'Documentation',
409 'baz': 'evil'}))
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000410
Georg Brandl48310cd2009-01-03 21:18:54 +0000411Defaults are available in all three types of ConfigParsers. They are used in
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000412interpolation if an option used is not defined elsewhere. ::
413
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000414 import configparser
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000415
416 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000417 config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000418 config.read('example.cfg')
Georg Brandl48310cd2009-01-03 21:18:54 +0000419
Georg Brandlf6945182008-02-01 11:56:49 +0000420 print(config.get('Section1', 'foo')) # -> "Python is fun!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000421 config.remove_option('Section1', 'bar')
422 config.remove_option('Section1', 'baz')
Georg Brandlf6945182008-02-01 11:56:49 +0000423 print(config.get('Section1', 'foo')) # -> "Life is hard!"
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000424
425The function ``opt_move`` below can be used to move options between sections::
426
427 def opt_move(config, section1, section2, option):
428 try:
429 config.set(section2, option, config.get(section1, option, 1))
Alexandre Vassalotti1d1eaa42008-05-14 22:59:42 +0000430 except configparser.NoSectionError:
Guido van Rossum2fd4f372007-11-29 18:43:05 +0000431 # Create non-existent section
432 config.add_section(section2)
433 opt_move(config, section1, section2, option)
Georg Brandl86def6c2008-01-21 20:36:10 +0000434 else:
435 config.remove_option(section1, option)