rest25/library/configparser.rst => rest262/library/configparser.rst
n1- 
2:mod:`ConfigParser` --- Configuration file parser
3=================================================
4
5.. module:: ConfigParser
6   :synopsis: Configuration file parser.
n6+ 
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
n12+.. note::
13+ 
14+   The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in
15+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
16+   converting your sources to 3.0.
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`
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
n32-:rfc:`822`; ``name=value`` is also accepted.  Note that leading whitespace is
n37+:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
33-removed from values. The optional values can contain format strings which refer
38+accepted.  Note that leading whitespace is removed from values. The optional
34-to other values in the same section, or values in a special ``DEFAULT`` section.
39+values can contain format strings which refer to other values in the same
35-Additional defaults can be provided on initialization and retrieval.  Lines
40+section, or values in a special ``DEFAULT`` section.  Additional defaults can be
36-beginning with ``'#'`` or ``';'`` are ignored and may be used to provide
41+provided on initialization and retrieval.  Lines beginning with ``'#'`` or
37-comments.
42+``';'`` are ignored and may be used to provide comments.
38
39For example::
40
41   [My Section]
42   foodir: %(dir)s/whatever
43   dir=frob
n49+   long: this value continues
50+      in the next line
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
n59+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.
52
n64+ 
53-.. class:: RawConfigParser([defaults])
65+.. class:: RawConfigParser([defaults[, dict_type]])
54
55   The basic configuration object.  When *defaults* is given, it is initialized
n56-   into the dictionary of intrinsic defaults.  This class does not support the
n68+   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
57-   magical interpolation behavior.
71+   support the magical interpolation behavior.
58
59   .. versionadded:: 2.3
60
n75+   .. versionchanged:: 2.6
76+      *dict_type* was added.
61
n78+ 
62-.. class:: ConfigParser([defaults])
79+.. class:: ConfigParser([defaults[, dict_type]])
63
64   Derived class of :class:`RawConfigParser` that implements the magical
65   interpolation feature and adds optional arguments to the :meth:`get` and
66   :meth:`items` methods.  The values in *defaults* must be appropriate for the
67   ``%()s`` string interpolation.  Note that *__name__* is an intrinsic default;
68   its value is the section name, and will override any value provided in
69   *defaults*.
70
71   All option names used in interpolation will be passed through the
72   :meth:`optionxform` method just like any other option name reference.  For
73   example, using the default implementation of :meth:`optionxform` (which converts
74   option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
75   equivalent.
76
77
n78-.. class:: SafeConfigParser([defaults])
n95+.. class:: SafeConfigParser([defaults[, dict_type]])
79
80   Derived class of :class:`ConfigParser` that implements a more-sane variant of
81   the magical interpolation feature.  This implementation is more predictable as
82   well. New applications should prefer this version if they don't need to be
83   compatible with older versions of Python.
84
n85-   .. % XXX Need to explain what's safer/more predictable about it.
n102+   .. XXX Need to explain what's safer/more predictable about it.
86
87   .. versionadded:: 2.3
88
89
90.. exception:: NoSectionError
91
92   Exception raised when a specified section is not found.
93
158.. _rawconfigparser-objects:
159
160RawConfigParser Objects
161-----------------------
162
163:class:`RawConfigParser` instances have the following methods:
164
165
n166-.. method:: XXX Class.defaults()
n183+.. method:: RawConfigParser.defaults()
167
168   Return a dictionary containing the instance-wide defaults.
169
170
n171-.. method:: XXX Class.sections()
n188+.. method:: RawConfigParser.sections()
172
173   Return a list of the sections available; ``DEFAULT`` is not included in the
174   list.
175
176
n177-.. method:: XXX Class.add_section(section)
n194+.. method:: RawConfigParser.add_section(section)
178
179   Add a section named *section* to the instance.  If a section by the given name
n180-   already exists, :exc:`DuplicateSectionError` is raised.
n197+   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.
181
n182- 
183-.. method:: XXX Class.has_section(section)
201+.. method:: RawConfigParser.has_section(section)
184
185   Indicates whether the named section is present in the configuration. The
186   ``DEFAULT`` section is not acknowledged.
187
188
n189-.. method:: XXX Class.options(section)
n207+.. method:: RawConfigParser.options(section)
190
191   Returns a list of options available in the specified *section*.
192
193
n194-.. method:: XXX Class.has_option(section, option)
n212+.. method:: RawConfigParser.has_option(section, option)
195
196   If the given section exists, and contains the given option, return
197   :const:`True`; otherwise return :const:`False`.
198
199   .. versionadded:: 1.6
200
201
n202-.. method:: XXX Class.read(filenames)
n220+.. method:: RawConfigParser.read(filenames)
203
204   Attempt to read and parse a list of filenames, returning a list of filenames
205   which were successfully parsed.  If *filenames* is a string or Unicode string,
206   it is treated as a single filename. If a file named in *filenames* cannot be
207   opened, that file will be ignored.  This is designed so that you can specify a
208   list of potential configuration file locations (for example, the current
209   directory, the user's home directory, and some system-wide directory), and all
210   existing configuration files in the list will be read.  If none of the named
218      config = ConfigParser.ConfigParser()
219      config.readfp(open('defaults.cfg'))
220      config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
221
222   .. versionchanged:: 2.4
223      Returns list of successfully parsed filenames.
224
225
n226-.. method:: XXX Class.readfp(fp[, filename])
n244+.. method:: RawConfigParser.readfp(fp[, filename])
227
228   Read and parse configuration data from the file or file-like object in *fp*
229   (only the :meth:`readline` method is used).  If *filename* is omitted and *fp*
230   has a :attr:`name` attribute, that is used for *filename*; the default is
231   ``<???>``.
232
233
n234-.. method:: XXX Class.get(section, option)
n252+.. method:: RawConfigParser.get(section, option)
235
236   Get an *option* value for the named *section*.
237
238
n239-.. method:: XXX Class.getint(section, option)
n257+.. method:: RawConfigParser.getint(section, option)
240
241   A convenience method which coerces the *option* in the specified *section* to an
242   integer.
243
244
n245-.. method:: XXX Class.getfloat(section, option)
n263+.. method:: RawConfigParser.getfloat(section, option)
246
247   A convenience method which coerces the *option* in the specified *section* to a
248   floating point number.
249
250
n251-.. method:: XXX Class.getboolean(section, option)
n269+.. method:: RawConfigParser.getboolean(section, option)
252
253   A convenience method which coerces the *option* in the specified *section* to a
254   Boolean value.  Note that the accepted values for the option are ``"1"``,
255   ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
256   and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
257   ``False``.  These string values are checked in a case-insensitive manner.  Any
258   other value will cause it to raise :exc:`ValueError`.
259
260
n261-.. method:: XXX Class.items(section)
n279+.. method:: RawConfigParser.items(section)
262
263   Return a list of ``(name, value)`` pairs for each option in the given *section*.
264
265
n266-.. method:: XXX Class.set(section, option, value)
n284+.. method:: RawConfigParser.set(section, option, value)
267
268   If the given section exists, set the given option to the specified value;
269   otherwise raise :exc:`NoSectionError`.  While it is possible to use
270   :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
271   true) for *internal* storage of non-string values, full functionality (including
272   interpolation and output to files) can only be achieved using string values.
273
274   .. versionadded:: 1.6
275
276
n277-.. method:: XXX Class.write(fileobject)
n295+.. method:: RawConfigParser.write(fileobject)
278
279   Write a representation of the configuration to the specified file object.  This
280   representation can be parsed by a future :meth:`read` call.
281
282   .. versionadded:: 1.6
283
284
n285-.. method:: XXX Class.remove_option(section, option)
n303+.. method:: RawConfigParser.remove_option(section, option)
286
287   Remove the specified *option* from the specified *section*. If the section does
288   not exist, raise :exc:`NoSectionError`.  If the option existed to be removed,
289   return :const:`True`; otherwise return :const:`False`.
290
291   .. versionadded:: 1.6
292
293
n294-.. method:: XXX Class.remove_section(section)
n312+.. method:: RawConfigParser.remove_section(section)
295
296   Remove the specified *section* from the configuration. If the section in fact
297   existed, return ``True``. Otherwise return ``False``.
298
299
n300-.. method:: XXX Class.optionxform(option)
n318+.. method:: RawConfigParser.optionxform(option)
301
302   Transforms the option name *option* as found in an input file or as passed in by
303   client code to the form that should be used in the internal structures.  The
304   default implementation returns a lower-case version of *option*; subclasses may
305   override this or client code can set an attribute of this name on instances to
306   affect this behavior.  Setting this to :func:`str`, for example, would make
307   option names case sensitive.
308
311
312ConfigParser Objects
313--------------------
314
315The :class:`ConfigParser` class extends some methods of the
316:class:`RawConfigParser` interface, adding some optional arguments.
317
318
n319-.. method:: XXX Class.get(section, option[, raw[, vars]])
n337+.. method:: ConfigParser.get(section, option[, raw[, vars]])
320
321   Get an *option* value for the named *section*.  All the ``'%'`` interpolations
322   are expanded in the return values, based on the defaults passed into the
323   constructor, as well as the options *vars* provided, unless the *raw* argument
324   is true.
325
326
n327-.. method:: XXX Class.items(section[, raw[, vars]])
n345+.. method:: ConfigParser.items(section[, raw[, vars]])
328
329   Return a list of ``(name, value)`` pairs for each option in the given *section*.
330   Optional arguments have the same meaning as for the :meth:`get` method.
331
332   .. versionadded:: 2.3
333
334
335.. _safeconfigparser-objects:
336
337SafeConfigParser Objects
338------------------------
339
340The :class:`SafeConfigParser` class implements the same extended interface as
341:class:`ConfigParser`, with the following addition:
342
343
n344-.. method:: XXX Class.set(section, option, value)
n362+.. method:: SafeConfigParser.set(section, option, value)
345
346   If the given section exists, set the given option to the specified value;
347   otherwise raise :exc:`NoSectionError`.  *value* must be a string (:class:`str`
348   or :class:`unicode`); if not, :exc:`TypeError` is raised.
349
350   .. versionadded:: 2.4
351
t370+ 
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)
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op