blob: b4c89e82102c51d470632e621a061b51c3f5b8a4 [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
Georg Brandl116aa622007-08-15 14:28:22 +000066
67.. class:: ConfigParser([defaults])
68
69 Derived class of :class:`RawConfigParser` that implements the magical
70 interpolation feature and adds optional arguments to the :meth:`get` and
71 :meth:`items` methods. The values in *defaults* must be appropriate for the
72 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default;
73 its value is the section name, and will override any value provided in
74 *defaults*.
75
76 All option names used in interpolation will be passed through the
77 :meth:`optionxform` method just like any other option name reference. For
78 example, using the default implementation of :meth:`optionxform` (which converts
79 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
80 equivalent.
81
82
83.. class:: SafeConfigParser([defaults])
84
85 Derived class of :class:`ConfigParser` that implements a more-sane variant of
86 the magical interpolation feature. This implementation is more predictable as
87 well. New applications should prefer this version if they don't need to be
88 compatible with older versions of Python.
89
90 .. % XXX Need to explain what's safer/more predictable about it.
91
Georg Brandl116aa622007-08-15 14:28:22 +000092
93.. exception:: NoSectionError
94
95 Exception raised when a specified section is not found.
96
97
98.. exception:: DuplicateSectionError
99
100 Exception raised if :meth:`add_section` is called with the name of a section
101 that is already present.
102
103
104.. exception:: NoOptionError
105
106 Exception raised when a specified option is not found in the specified section.
107
108
109.. exception:: InterpolationError
110
111 Base class for exceptions raised when problems occur performing string
112 interpolation.
113
114
115.. exception:: InterpolationDepthError
116
117 Exception raised when string interpolation cannot be completed because the
118 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
119 :exc:`InterpolationError`.
120
121
122.. exception:: InterpolationMissingOptionError
123
124 Exception raised when an option referenced from a value does not exist. Subclass
125 of :exc:`InterpolationError`.
126
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128.. exception:: InterpolationSyntaxError
129
130 Exception raised when the source text into which substitutions are made does not
131 conform to the required syntax. Subclass of :exc:`InterpolationError`.
132
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134.. exception:: MissingSectionHeaderError
135
136 Exception raised when attempting to parse a file which has no section headers.
137
138
139.. exception:: ParsingError
140
141 Exception raised when errors occur attempting to parse a file.
142
143
144.. data:: MAX_INTERPOLATION_DEPTH
145
146 The maximum depth for recursive interpolation for :meth:`get` when the *raw*
147 parameter is false. This is relevant only for the :class:`ConfigParser` class.
148
149
150.. seealso::
151
152 Module :mod:`shlex`
153 Support for a creating Unix shell-like mini-languages which can be used as an
154 alternate format for application configuration files.
155
156
157.. _rawconfigparser-objects:
158
159RawConfigParser Objects
160-----------------------
161
162:class:`RawConfigParser` instances have the following methods:
163
164
165.. method:: RawConfigParser.defaults()
166
167 Return a dictionary containing the instance-wide defaults.
168
169
170.. method:: RawConfigParser.sections()
171
172 Return a list of the sections available; ``DEFAULT`` is not included in the
173 list.
174
175
176.. method:: RawConfigParser.add_section(section)
177
178 Add a section named *section* to the instance. If a section by the given name
179 already exists, :exc:`DuplicateSectionError` is raised.
180
181
182.. method:: RawConfigParser.has_section(section)
183
184 Indicates whether the named section is present in the configuration. The
185 ``DEFAULT`` section is not acknowledged.
186
187
188.. method:: RawConfigParser.options(section)
189
190 Returns a list of options available in the specified *section*.
191
192
193.. method:: RawConfigParser.has_option(section, option)
194
195 If the given section exists, and contains the given option, return
196 :const:`True`; otherwise return :const:`False`.
197
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199.. method:: RawConfigParser.read(filenames)
200
201 Attempt to read and parse a list of filenames, returning a list of filenames
202 which were successfully parsed. If *filenames* is a string or Unicode string,
203 it is treated as a single filename. If a file named in *filenames* cannot be
204 opened, that file will be ignored. This is designed so that you can specify a
205 list of potential configuration file locations (for example, the current
206 directory, the user's home directory, and some system-wide directory), and all
207 existing configuration files in the list will be read. If none of the named
208 files exist, the :class:`ConfigParser` instance will contain an empty dataset.
209 An application which requires initial values to be loaded from a file should
210 load the required file or files using :meth:`readfp` before calling :meth:`read`
211 for any optional files::
212
213 import ConfigParser, os
214
215 config = ConfigParser.ConfigParser()
216 config.readfp(open('defaults.cfg'))
217 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220.. method:: RawConfigParser.readfp(fp[, filename])
221
222 Read and parse configuration data from the file or file-like object in *fp*
223 (only the :meth:`readline` method is used). If *filename* is omitted and *fp*
224 has a :attr:`name` attribute, that is used for *filename*; the default is
225 ``<???>``.
226
227
228.. method:: RawConfigParser.get(section, option)
229
230 Get an *option* value for the named *section*.
231
232
233.. method:: RawConfigParser.getint(section, option)
234
235 A convenience method which coerces the *option* in the specified *section* to an
236 integer.
237
238
239.. method:: RawConfigParser.getfloat(section, option)
240
241 A convenience method which coerces the *option* in the specified *section* to a
242 floating point number.
243
244
245.. method:: RawConfigParser.getboolean(section, option)
246
247 A convenience method which coerces the *option* in the specified *section* to a
248 Boolean value. Note that the accepted values for the option are ``"1"``,
249 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
250 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
251 ``False``. These string values are checked in a case-insensitive manner. Any
252 other value will cause it to raise :exc:`ValueError`.
253
254
255.. method:: RawConfigParser.items(section)
256
257 Return a list of ``(name, value)`` pairs for each option in the given *section*.
258
259
260.. method:: RawConfigParser.set(section, option, value)
261
262 If the given section exists, set the given option to the specified value;
263 otherwise raise :exc:`NoSectionError`. While it is possible to use
264 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
265 true) for *internal* storage of non-string values, full functionality (including
266 interpolation and output to files) can only be achieved using string values.
267
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269.. method:: RawConfigParser.write(fileobject)
270
271 Write a representation of the configuration to the specified file object. This
272 representation can be parsed by a future :meth:`read` call.
273
Georg Brandl116aa622007-08-15 14:28:22 +0000274
275.. method:: RawConfigParser.remove_option(section, option)
276
277 Remove the specified *option* from the specified *section*. If the section does
278 not exist, raise :exc:`NoSectionError`. If the option existed to be removed,
279 return :const:`True`; otherwise return :const:`False`.
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282.. method:: RawConfigParser.remove_section(section)
283
284 Remove the specified *section* from the configuration. If the section in fact
285 existed, return ``True``. Otherwise return ``False``.
286
287
288.. method:: RawConfigParser.optionxform(option)
289
290 Transforms the option name *option* as found in an input file or as passed in by
291 client code to the form that should be used in the internal structures. The
292 default implementation returns a lower-case version of *option*; subclasses may
293 override this or client code can set an attribute of this name on instances to
294 affect this behavior. Setting this to :func:`str`, for example, would make
295 option names case sensitive.
296
297
298.. _configparser-objects:
299
300ConfigParser Objects
301--------------------
302
303The :class:`ConfigParser` class extends some methods of the
304:class:`RawConfigParser` interface, adding some optional arguments.
305
306
307.. method:: ConfigParser.get(section, option[, raw[, vars]])
308
309 Get an *option* value for the named *section*. All the ``'%'`` interpolations
310 are expanded in the return values, based on the defaults passed into the
311 constructor, as well as the options *vars* provided, unless the *raw* argument
312 is true.
313
314
315.. method:: ConfigParser.items(section[, raw[, vars]])
316
317 Return a list of ``(name, value)`` pairs for each option in the given *section*.
318 Optional arguments have the same meaning as for the :meth:`get` method.
319
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321.. _safeconfigparser-objects:
322
323SafeConfigParser Objects
324------------------------
325
326The :class:`SafeConfigParser` class implements the same extended interface as
327:class:`ConfigParser`, with the following addition:
328
329
330.. method:: SafeConfigParser.set(section, option, value)
331
332 If the given section exists, set the given option to the specified value;
333 otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str`
334 or :class:`unicode`); if not, :exc:`TypeError` is raised.
335