blob: dd91d594b4a4f7b07d33b0681dfb02d58b989e34 [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
32:rfc:`822`; ``name=value`` is also accepted. Note that leading whitespace is
33removed from values. The optional values can contain format strings which refer
34to other values in the same section, or values in a special ``DEFAULT`` section.
35Additional defaults can be provided on initialization and retrieval. Lines
36beginning with ``'#'`` or ``';'`` are ignored and may be used to provide
37comments.
38
39For example::
40
41 [My Section]
42 foodir: %(dir)s/whatever
43 dir=frob
44
45would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
46All reference expansions are done on demand.
47
48Default values can be specified by passing them into the :class:`ConfigParser`
49constructor as a dictionary. Additional defaults may be passed into the
50:meth:`get` method which will override all others.
51
52Sections are normally stored in a builtin dictionary. An alternative dictionary
53type can be passed to the :class:`ConfigParser` constructor. For example, if a
54dictionary type is passed that sorts its keys, the sections will be sorted on
55write-back, as will be the keys within each section.
56
57
58.. class:: RawConfigParser([defaults[, dict_type]])
59
60 The basic configuration object. When *defaults* is given, it is initialized
61 into the dictionary of intrinsic defaults. When *dict_type* is given, it will
62 be used to create the dictionary objects for the list of sections, for the
63 options within a section, and for the default values. This class does not
64 support the magical interpolation behavior.
65
66 .. versionadded:: 2.3
67
68 .. versionchanged:: 2.6
69 *dict_type* was added.
70
71
72.. class:: ConfigParser([defaults])
73
74 Derived class of :class:`RawConfigParser` that implements the magical
75 interpolation feature and adds optional arguments to the :meth:`get` and
76 :meth:`items` methods. The values in *defaults* must be appropriate for the
77 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
78 its value is the section name, and will override any value provided in
79 *defaults*.
80
81 All option names used in interpolation will be passed through the
82 :meth:`optionxform` method just like any other option name reference. For
83 example, using the default implementation of :meth:`optionxform` (which converts
84 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
85 equivalent.
86
87
88.. class:: SafeConfigParser([defaults])
89
90 Derived class of :class:`ConfigParser` that implements a more-sane variant of
91 the magical interpolation feature. This implementation is more predictable as
92 well. New applications should prefer this version if they don't need to be
93 compatible with older versions of Python.
94
95 .. % XXX Need to explain what's safer/more predictable about it.
96
97 .. versionadded:: 2.3
98
99
100.. exception:: NoSectionError
101
102 Exception raised when a specified section is not found.
103
104
105.. exception:: DuplicateSectionError
106
107 Exception raised if :meth:`add_section` is called with the name of a section
108 that is already present.
109
110
111.. exception:: NoOptionError
112
113 Exception raised when a specified option is not found in the specified section.
114
115
116.. exception:: InterpolationError
117
118 Base class for exceptions raised when problems occur performing string
119 interpolation.
120
121
122.. exception:: InterpolationDepthError
123
124 Exception raised when string interpolation cannot be completed because the
125 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
126 :exc:`InterpolationError`.
127
128
129.. exception:: InterpolationMissingOptionError
130
131 Exception raised when an option referenced from a value does not exist. Subclass
132 of :exc:`InterpolationError`.
133
134 .. versionadded:: 2.3
135
136
137.. exception:: InterpolationSyntaxError
138
139 Exception raised when the source text into which substitutions are made does not
140 conform to the required syntax. Subclass of :exc:`InterpolationError`.
141
142 .. versionadded:: 2.3
143
144
145.. exception:: MissingSectionHeaderError
146
147 Exception raised when attempting to parse a file which has no section headers.
148
149
150.. exception:: ParsingError
151
152 Exception raised when errors occur attempting to parse a file.
153
154
155.. data:: MAX_INTERPOLATION_DEPTH
156
157 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
158 parameter is false. This is relevant only for the :class:`ConfigParser` class.
159
160
161.. seealso::
162
163 Module :mod:`shlex`
164 Support for a creating Unix shell-like mini-languages which can be used as an
165 alternate format for application configuration files.
166
167
168.. _rawconfigparser-objects:
169
170RawConfigParser Objects
171-----------------------
172
173:class:`RawConfigParser` instances have the following methods:
174
175
176.. method:: RawConfigParser.defaults()
177
178 Return a dictionary containing the instance-wide defaults.
179
180
181.. method:: RawConfigParser.sections()
182
183 Return a list of the sections available; ``DEFAULT`` is not included in the
184 list.
185
186
187.. method:: RawConfigParser.add_section(section)
188
189 Add a section named *section* to the instance. If a section by the given name
190 already exists, :exc:`DuplicateSectionError` is raised.
191
192
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
209 .. versionadded:: 1.6
210
211
212.. method:: RawConfigParser.read(filenames)
213
214 Attempt to read and parse a list of filenames, returning a list of filenames
215 which were successfully parsed. If *filenames* is a string or Unicode string,
216 it is treated as a single filename. If a file named in *filenames* cannot be
217 opened, that file will be ignored. This is designed so that you can specify a
218 list of potential configuration file locations (for example, the current
219 directory, the user's home directory, and some system-wide directory), and all
220 existing configuration files in the list will be read. If none of the named
221 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
222 An application which requires initial values to be loaded from a file should
223 load the required file or files using :meth:`readfp` before calling :meth:`read`
224 for any optional files::
225
226 import ConfigParser, os
227
228 config = ConfigParser.ConfigParser()
229 config.readfp(open('defaults.cfg'))
230 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
231
232 .. versionchanged:: 2.4
233 Returns list of successfully parsed filenames.
234
235
236.. method:: RawConfigParser.readfp(fp[, filename])
237
238 Read and parse configuration data from the file or file-like object in *fp*
239 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
240 has a :attr:`name` attribute, that is used for *filename*; the default is
241 ``<???>``.
242
243
244.. method:: RawConfigParser.get(section, option)
245
246 Get an *option* value for the named *section*.
247
248
249.. method:: RawConfigParser.getint(section, option)
250
251 A convenience method which coerces the *option* in the specified *section* to an
252 integer.
253
254
255.. method:: RawConfigParser.getfloat(section, option)
256
257 A convenience method which coerces the *option* in the specified *section* to a
258 floating point number.
259
260
261.. method:: RawConfigParser.getboolean(section, option)
262
263 A convenience method which coerces the *option* in the specified *section* to a
264 Boolean value. Note that the accepted values for the option are ``"1"``,
265 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
266 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
267 ``False``. These string values are checked in a case-insensitive manner. Any
268 other value will cause it to raise :exc:`ValueError`.
269
270
271.. method:: RawConfigParser.items(section)
272
273 Return a list of ``(name, value)`` pairs for each option in the given *section*.
274
275
276.. method:: RawConfigParser.set(section, option, value)
277
278 If the given section exists, set the given option to the specified value;
279 otherwise raise :exc:`NoSectionError`. While it is possible to use
280 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
281 true) for *internal* storage of non-string values, full functionality (including
282 interpolation and output to files) can only be achieved using string values.
283
284 .. versionadded:: 1.6
285
286
287.. method:: RawConfigParser.write(fileobject)
288
289 Write a representation of the configuration to the specified file object. This
290 representation can be parsed by a future :meth:`read` call.
291
292 .. versionadded:: 1.6
293
294
295.. method:: RawConfigParser.remove_option(section, option)
296
297 Remove the specified *option* from the specified *section*. If the section does
298 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
299 return :const:`True`; otherwise return :const:`False`.
300
301 .. versionadded:: 1.6
302
303
304.. method:: RawConfigParser.remove_section(section)
305
306 Remove the specified *section* from the configuration. If the section in fact
307 existed, return ``True``. Otherwise return ``False``.
308
309
310.. method:: RawConfigParser.optionxform(option)
311
312 Transforms the option name *option* as found in an input file or as passed in by
313 client code to the form that should be used in the internal structures. The
314 default implementation returns a lower-case version of *option*; subclasses may
315 override this or client code can set an attribute of this name on instances to
316 affect this behavior. Setting this to :func:`str`, for example, would make
317 option names case sensitive.
318
319
320.. _configparser-objects:
321
322ConfigParser Objects
323--------------------
324
325The :class:`ConfigParser` class extends some methods of the
326:class:`RawConfigParser` interface, adding some optional arguments.
327
328
329.. method:: ConfigParser.get(section, option[, raw[, vars]])
330
331 Get an *option* value for the named *section*. All the ``'%'`` interpolations
332 are expanded in the return values, based on the defaults passed into the
333 constructor, as well as the options *vars* provided, unless the *raw* argument
334 is true.
335
336
337.. method:: ConfigParser.items(section[, raw[, vars]])
338
339 Return a list of ``(name, value)`` pairs for each option in the given *section*.
340 Optional arguments have the same meaning as for the :meth:`get` method.
341
342 .. versionadded:: 2.3
343
344
345.. _safeconfigparser-objects:
346
347SafeConfigParser Objects
348------------------------
349
350The :class:`SafeConfigParser` class implements the same extended interface as
351:class:`ConfigParser`, with the following addition:
352
353
354.. method:: SafeConfigParser.set(section, option, value)
355
356 If the given section exists, set the given option to the specified value;
357 otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str`
358 or :class:`unicode`); if not, :exc:`TypeError` is raised.
359
360 .. versionadded:: 2.4
361