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