|
1 :mod:`ConfigParser` --- Configuration file parser |
|
2 ================================================= |
|
3 |
|
4 .. module:: ConfigParser |
|
5 :synopsis: Configuration file parser. |
|
6 |
|
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 .. note:: |
|
13 |
|
14 The :mod:`ConfigParser` module has been renamed to `configparser` in Python |
|
15 3.0. The :term:`2to3` tool will automatically adapt imports when converting |
|
16 your sources to 3.0. |
|
17 |
|
18 .. index:: |
|
19 pair: .ini; file |
|
20 pair: configuration; file |
|
21 single: ini file |
|
22 single: Windows ini file |
|
23 |
|
24 This module defines the class :class:`ConfigParser`. The :class:`ConfigParser` |
|
25 class implements a basic configuration file parser language which provides a |
|
26 structure similar to what you would find on Microsoft Windows INI files. You |
|
27 can use this to write Python programs which can be customized by end users |
|
28 easily. |
|
29 |
|
30 .. warning:: |
|
31 |
|
32 This library does *not* interpret or write the value-type prefixes used in the |
|
33 Windows Registry extended version of INI syntax. |
|
34 |
|
35 The configuration file consists of sections, led by a ``[section]`` header and |
|
36 followed by ``name: value`` entries, with continuations in the style of |
|
37 :rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also |
|
38 accepted. Note that leading whitespace is removed from values. The optional |
|
39 values can contain format strings which refer to other values in the same |
|
40 section, or values in a special ``DEFAULT`` section. Additional defaults can be |
|
41 provided on initialization and retrieval. Lines beginning with ``'#'`` or |
|
42 ``';'`` are ignored and may be used to provide comments. |
|
43 |
|
44 For example:: |
|
45 |
|
46 [My Section] |
|
47 foodir: %(dir)s/whatever |
|
48 dir=frob |
|
49 long: this value continues |
|
50 in the next line |
|
51 |
|
52 would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case). |
|
53 All reference expansions are done on demand. |
|
54 |
|
55 Default values can be specified by passing them into the :class:`ConfigParser` |
|
56 constructor as a dictionary. Additional defaults may be passed into the |
|
57 :meth:`get` method which will override all others. |
|
58 |
|
59 Sections are normally stored in a builtin dictionary. An alternative dictionary |
|
60 type can be passed to the :class:`ConfigParser` constructor. For example, if a |
|
61 dictionary type is passed that sorts its keys, the sections will be sorted on |
|
62 write-back, as will be the keys within each section. |
|
63 |
|
64 |
|
65 .. class:: RawConfigParser([defaults[, dict_type]]) |
|
66 |
|
67 The basic configuration object. When *defaults* is given, it is initialized |
|
68 into the dictionary of intrinsic defaults. When *dict_type* is given, it will |
|
69 be used to create the dictionary objects for the list of sections, for the |
|
70 options within a section, and for the default values. This class does not |
|
71 support the magical interpolation behavior. |
|
72 |
|
73 .. versionadded:: 2.3 |
|
74 |
|
75 .. versionchanged:: 2.6 |
|
76 *dict_type* was added. |
|
77 |
|
78 |
|
79 .. class:: ConfigParser([defaults]) |
|
80 |
|
81 Derived class of :class:`RawConfigParser` that implements the magical |
|
82 interpolation feature and adds optional arguments to the :meth:`get` and |
|
83 :meth:`items` methods. The values in *defaults* must be appropriate for the |
|
84 ``%()s`` string interpolation. Note that *__name__* is an intrinsic default; |
|
85 its value is the section name, and will override any value provided in |
|
86 *defaults*. |
|
87 |
|
88 All option names used in interpolation will be passed through the |
|
89 :meth:`optionxform` method just like any other option name reference. For |
|
90 example, using the default implementation of :meth:`optionxform` (which converts |
|
91 option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are |
|
92 equivalent. |
|
93 |
|
94 |
|
95 .. class:: SafeConfigParser([defaults]) |
|
96 |
|
97 Derived class of :class:`ConfigParser` that implements a more-sane variant of |
|
98 the magical interpolation feature. This implementation is more predictable as |
|
99 well. New applications should prefer this version if they don't need to be |
|
100 compatible with older versions of Python. |
|
101 |
|
102 .. XXX Need to explain what's safer/more predictable about it. |
|
103 |
|
104 .. versionadded:: 2.3 |
|
105 |
|
106 |
|
107 .. exception:: NoSectionError |
|
108 |
|
109 Exception raised when a specified section is not found. |
|
110 |
|
111 |
|
112 .. exception:: DuplicateSectionError |
|
113 |
|
114 Exception raised if :meth:`add_section` is called with the name of a section |
|
115 that is already present. |
|
116 |
|
117 |
|
118 .. exception:: NoOptionError |
|
119 |
|
120 Exception raised when a specified option is not found in the specified section. |
|
121 |
|
122 |
|
123 .. exception:: InterpolationError |
|
124 |
|
125 Base class for exceptions raised when problems occur performing string |
|
126 interpolation. |
|
127 |
|
128 |
|
129 .. exception:: InterpolationDepthError |
|
130 |
|
131 Exception raised when string interpolation cannot be completed because the |
|
132 number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of |
|
133 :exc:`InterpolationError`. |
|
134 |
|
135 |
|
136 .. exception:: InterpolationMissingOptionError |
|
137 |
|
138 Exception raised when an option referenced from a value does not exist. Subclass |
|
139 of :exc:`InterpolationError`. |
|
140 |
|
141 .. versionadded:: 2.3 |
|
142 |
|
143 |
|
144 .. exception:: InterpolationSyntaxError |
|
145 |
|
146 Exception raised when the source text into which substitutions are made does not |
|
147 conform to the required syntax. Subclass of :exc:`InterpolationError`. |
|
148 |
|
149 .. versionadded:: 2.3 |
|
150 |
|
151 |
|
152 .. exception:: MissingSectionHeaderError |
|
153 |
|
154 Exception raised when attempting to parse a file which has no section headers. |
|
155 |
|
156 |
|
157 .. exception:: ParsingError |
|
158 |
|
159 Exception raised when errors occur attempting to parse a file. |
|
160 |
|
161 |
|
162 .. data:: MAX_INTERPOLATION_DEPTH |
|
163 |
|
164 The maximum depth for recursive interpolation for :meth:`get` when the *raw* |
|
165 parameter is false. This is relevant only for the :class:`ConfigParser` class. |
|
166 |
|
167 |
|
168 .. seealso:: |
|
169 |
|
170 Module :mod:`shlex` |
|
171 Support for a creating Unix shell-like mini-languages which can be used as an |
|
172 alternate format for application configuration files. |
|
173 |
|
174 |
|
175 .. _rawconfigparser-objects: |
|
176 |
|
177 RawConfigParser Objects |
|
178 ----------------------- |
|
179 |
|
180 :class:`RawConfigParser` instances have the following methods: |
|
181 |
|
182 |
|
183 .. method:: RawConfigParser.defaults() |
|
184 |
|
185 Return a dictionary containing the instance-wide defaults. |
|
186 |
|
187 |
|
188 .. method:: RawConfigParser.sections() |
|
189 |
|
190 Return a list of the sections available; ``DEFAULT`` is not included in the |
|
191 list. |
|
192 |
|
193 |
|
194 .. method:: RawConfigParser.add_section(section) |
|
195 |
|
196 Add a section named *section* to the instance. If a section by the given name |
|
197 already exists, :exc:`DuplicateSectionError` is raised. If the name |
|
198 ``DEFAULT`` (or any of it's case-insensitive variants) is passed, |
|
199 :exc:`ValueError` is raised. |
|
200 |
|
201 .. method:: RawConfigParser.has_section(section) |
|
202 |
|
203 Indicates whether the named section is present in the configuration. The |
|
204 ``DEFAULT`` section is not acknowledged. |
|
205 |
|
206 |
|
207 .. method:: RawConfigParser.options(section) |
|
208 |
|
209 Returns a list of options available in the specified *section*. |
|
210 |
|
211 |
|
212 .. method:: RawConfigParser.has_option(section, option) |
|
213 |
|
214 If the given section exists, and contains the given option, return |
|
215 :const:`True`; otherwise return :const:`False`. |
|
216 |
|
217 .. versionadded:: 1.6 |
|
218 |
|
219 |
|
220 .. method:: RawConfigParser.read(filenames) |
|
221 |
|
222 Attempt to read and parse a list of filenames, returning a list of filenames |
|
223 which were successfully parsed. If *filenames* is a string or Unicode string, |
|
224 it is treated as a single filename. If a file named in *filenames* cannot be |
|
225 opened, that file will be ignored. This is designed so that you can specify a |
|
226 list of potential configuration file locations (for example, the current |
|
227 directory, the user's home directory, and some system-wide directory), and all |
|
228 existing configuration files in the list will be read. If none of the named |
|
229 files exist, the :class:`ConfigParser` instance will contain an empty dataset. |
|
230 An application which requires initial values to be loaded from a file should |
|
231 load the required file or files using :meth:`readfp` before calling :meth:`read` |
|
232 for any optional files:: |
|
233 |
|
234 import ConfigParser, os |
|
235 |
|
236 config = ConfigParser.ConfigParser() |
|
237 config.readfp(open('defaults.cfg')) |
|
238 config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')]) |
|
239 |
|
240 .. versionchanged:: 2.4 |
|
241 Returns list of successfully parsed filenames. |
|
242 |
|
243 |
|
244 .. method:: RawConfigParser.readfp(fp[, filename]) |
|
245 |
|
246 Read and parse configuration data from the file or file-like object in *fp* |
|
247 (only the :meth:`readline` method is used). If *filename* is omitted and *fp* |
|
248 has a :attr:`name` attribute, that is used for *filename*; the default is |
|
249 ``<???>``. |
|
250 |
|
251 |
|
252 .. method:: RawConfigParser.get(section, option) |
|
253 |
|
254 Get an *option* value for the named *section*. |
|
255 |
|
256 |
|
257 .. method:: RawConfigParser.getint(section, option) |
|
258 |
|
259 A convenience method which coerces the *option* in the specified *section* to an |
|
260 integer. |
|
261 |
|
262 |
|
263 .. method:: RawConfigParser.getfloat(section, option) |
|
264 |
|
265 A convenience method which coerces the *option* in the specified *section* to a |
|
266 floating point number. |
|
267 |
|
268 |
|
269 .. method:: RawConfigParser.getboolean(section, option) |
|
270 |
|
271 A convenience method which coerces the *option* in the specified *section* to a |
|
272 Boolean value. Note that the accepted values for the option are ``"1"``, |
|
273 ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``, |
|
274 and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return |
|
275 ``False``. These string values are checked in a case-insensitive manner. Any |
|
276 other value will cause it to raise :exc:`ValueError`. |
|
277 |
|
278 |
|
279 .. method:: RawConfigParser.items(section) |
|
280 |
|
281 Return a list of ``(name, value)`` pairs for each option in the given *section*. |
|
282 |
|
283 |
|
284 .. method:: RawConfigParser.set(section, option, value) |
|
285 |
|
286 If the given section exists, set the given option to the specified value; |
|
287 otherwise raise :exc:`NoSectionError`. While it is possible to use |
|
288 :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to |
|
289 true) for *internal* storage of non-string values, full functionality (including |
|
290 interpolation and output to files) can only be achieved using string values. |
|
291 |
|
292 .. versionadded:: 1.6 |
|
293 |
|
294 |
|
295 .. method:: RawConfigParser.write(fileobject) |
|
296 |
|
297 Write a representation of the configuration to the specified file object. This |
|
298 representation can be parsed by a future :meth:`read` call. |
|
299 |
|
300 .. versionadded:: 1.6 |
|
301 |
|
302 |
|
303 .. method:: RawConfigParser.remove_option(section, option) |
|
304 |
|
305 Remove the specified *option* from the specified *section*. If the section does |
|
306 not exist, raise :exc:`NoSectionError`. If the option existed to be removed, |
|
307 return :const:`True`; otherwise return :const:`False`. |
|
308 |
|
309 .. versionadded:: 1.6 |
|
310 |
|
311 |
|
312 .. method:: RawConfigParser.remove_section(section) |
|
313 |
|
314 Remove the specified *section* from the configuration. If the section in fact |
|
315 existed, return ``True``. Otherwise return ``False``. |
|
316 |
|
317 |
|
318 .. method:: RawConfigParser.optionxform(option) |
|
319 |
|
320 Transforms the option name *option* as found in an input file or as passed in by |
|
321 client code to the form that should be used in the internal structures. The |
|
322 default implementation returns a lower-case version of *option*; subclasses may |
|
323 override this or client code can set an attribute of this name on instances to |
|
324 affect this behavior. Setting this to :func:`str`, for example, would make |
|
325 option names case sensitive. |
|
326 |
|
327 |
|
328 .. _configparser-objects: |
|
329 |
|
330 ConfigParser Objects |
|
331 -------------------- |
|
332 |
|
333 The :class:`ConfigParser` class extends some methods of the |
|
334 :class:`RawConfigParser` interface, adding some optional arguments. |
|
335 |
|
336 |
|
337 .. method:: ConfigParser.get(section, option[, raw[, vars]]) |
|
338 |
|
339 Get an *option* value for the named *section*. All the ``'%'`` interpolations |
|
340 are expanded in the return values, based on the defaults passed into the |
|
341 constructor, as well as the options *vars* provided, unless the *raw* argument |
|
342 is true. |
|
343 |
|
344 |
|
345 .. method:: ConfigParser.items(section[, raw[, vars]]) |
|
346 |
|
347 Return a list of ``(name, value)`` pairs for each option in the given *section*. |
|
348 Optional arguments have the same meaning as for the :meth:`get` method. |
|
349 |
|
350 .. versionadded:: 2.3 |
|
351 |
|
352 |
|
353 .. _safeconfigparser-objects: |
|
354 |
|
355 SafeConfigParser Objects |
|
356 ------------------------ |
|
357 |
|
358 The :class:`SafeConfigParser` class implements the same extended interface as |
|
359 :class:`ConfigParser`, with the following addition: |
|
360 |
|
361 |
|
362 .. method:: SafeConfigParser.set(section, option, value) |
|
363 |
|
364 If the given section exists, set the given option to the specified value; |
|
365 otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str` |
|
366 or :class:`unicode`); if not, :exc:`TypeError` is raised. |
|
367 |
|
368 .. versionadded:: 2.4 |
|
369 |
|
370 |
|
371 Examples |
|
372 -------- |
|
373 |
|
374 An example of writing to a configuration file:: |
|
375 |
|
376 import ConfigParser |
|
377 |
|
378 config = ConfigParser.RawConfigParser() |
|
379 |
|
380 # When adding sections or items, add them in the reverse order of |
|
381 # how you want them to be displayed in the actual file. |
|
382 # In addition, please note that using RawConfigParser's and the raw |
|
383 # mode of ConfigParser's respective set functions, you can assign |
|
384 # non-string values to keys internally, but will receive an error |
|
385 # when attempting to write to a file or when you get it in non-raw |
|
386 # mode. SafeConfigParser does not allow such assignments to take place. |
|
387 config.add_section('Section1') |
|
388 config.set('Section1', 'int', '15') |
|
389 config.set('Section1', 'bool', 'true') |
|
390 config.set('Section1', 'float', '3.1415') |
|
391 config.set('Section1', 'baz', 'fun') |
|
392 config.set('Section1', 'bar', 'Python') |
|
393 config.set('Section1', 'foo', '%(bar)s is %(baz)s!') |
|
394 |
|
395 # Writing our configuration file to 'example.cfg' |
|
396 with open('example.cfg', 'wb') as configfile: |
|
397 config.write(configfile) |
|
398 |
|
399 An example of reading the configuration file again:: |
|
400 |
|
401 import ConfigParser |
|
402 |
|
403 config = ConfigParser.RawConfigParser() |
|
404 config.read('example.cfg') |
|
405 |
|
406 # getfloat() raises an exception if the value is not a float |
|
407 # getint() and getboolean() also do this for their respective types |
|
408 float = config.getfloat('Section1', 'float') |
|
409 int = config.getint('Section1', 'int') |
|
410 print float + int |
|
411 |
|
412 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. |
|
413 # This is because we are using a RawConfigParser(). |
|
414 if config.getboolean('Section1', 'bool'): |
|
415 print config.get('Section1', 'foo') |
|
416 |
|
417 To get interpolation, you will need to use a :class:`ConfigParser` or |
|
418 :class:`SafeConfigParser`:: |
|
419 |
|
420 import ConfigParser |
|
421 |
|
422 config = ConfigParser.ConfigParser() |
|
423 config.read('example.cfg') |
|
424 |
|
425 # Set the third, optional argument of get to 1 if you wish to use raw mode. |
|
426 print config.get('Section1', 'foo', 0) # -> "Python is fun!" |
|
427 print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!" |
|
428 |
|
429 # The optional fourth argument is a dict with members that will take |
|
430 # precedence in interpolation. |
|
431 print config.get('Section1', 'foo', 0, {'bar': 'Documentation', |
|
432 'baz': 'evil'}) |
|
433 |
|
434 Defaults are available in all three types of ConfigParsers. They are used in |
|
435 interpolation if an option used is not defined elsewhere. :: |
|
436 |
|
437 import ConfigParser |
|
438 |
|
439 # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each |
|
440 config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'}) |
|
441 config.read('example.cfg') |
|
442 |
|
443 print config.get('Section1', 'foo') # -> "Python is fun!" |
|
444 config.remove_option('Section1', 'bar') |
|
445 config.remove_option('Section1', 'baz') |
|
446 print config.get('Section1', 'foo') # -> "Life is hard!" |
|
447 |
|
448 The function ``opt_move`` below can be used to move options between sections:: |
|
449 |
|
450 def opt_move(config, section1, section2, option): |
|
451 try: |
|
452 config.set(section2, option, config.get(section1, option, 1)) |
|
453 except ConfigParser.NoSectionError: |
|
454 # Create non-existent section |
|
455 config.add_section(section2) |
|
456 opt_move(config, section1, section2, option) |
|
457 else: |
|
458 config.remove_option(section1, option) |