add further note about what's passed to optionxform
[python.git] / Doc / library / configparser.rst
blob2d8aa50e4c290de5ba1e8c58710ebf03e618d79b
1 :mod:`ConfigParser` --- Configuration file parser
2 =================================================
4 .. module:: ConfigParser
5    :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>
12 .. note::
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.
18 .. index::
19    pair: .ini; file
20    pair: configuration; file
21    single: ini file
22    single: Windows ini file
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.
30 .. note::
32    This library does *not* interpret or write the value-type prefixes used in
33    the Windows Registry extended version of INI syntax.
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.
44 For example::
46    [My Section]
47    foodir: %(dir)s/whatever
48    dir=frob
49    long: this value continues
50       in the next line
52 would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
53 All reference expansions are done on demand.
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.
59 Sections are normally stored in a built-in 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.
65 .. class:: RawConfigParser([defaults[, dict_type]])
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.
73    .. versionadded:: 2.3
75    .. versionchanged:: 2.6
76       *dict_type* was added.
78    .. versionchanged:: 2.7
79       The default *dict_type* is :class:`collections.OrderedDict`.
82 .. class:: ConfigParser([defaults[, dict_type]])
84    Derived class of :class:`RawConfigParser` that implements the magical
85    interpolation feature and adds optional arguments to the :meth:`get` and
86    :meth:`items` methods.  The values in *defaults* must be appropriate for the
87    ``%()s`` string interpolation.  Note that *__name__* is an intrinsic default;
88    its value is the section name, and will override any value provided in
89    *defaults*.
91    All option names used in interpolation will be passed through the
92    :meth:`optionxform` method just like any other option name reference.  For
93    example, using the default implementation of :meth:`optionxform` (which converts
94    option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are
95    equivalent.
97    .. versionadded:: 2.3
99    .. versionchanged:: 2.6
100       *dict_type* was added.
102    .. versionchanged:: 2.7
103       The default *dict_type* is :class:`collections.OrderedDict`.
106 .. class:: SafeConfigParser([defaults[, dict_type]])
108    Derived class of :class:`ConfigParser` that implements a more-sane variant of
109    the magical interpolation feature.  This implementation is more predictable as
110    well. New applications should prefer this version if they don't need to be
111    compatible with older versions of Python.
113    .. XXX Need to explain what's safer/more predictable about it.
115    .. versionadded:: 2.3
117    .. versionchanged:: 2.6
118       *dict_type* was added.
120    .. versionchanged:: 2.7
121       The default *dict_type* is :class:`collections.OrderedDict`.
124 .. exception:: NoSectionError
126    Exception raised when a specified section is not found.
129 .. exception:: DuplicateSectionError
131    Exception raised if :meth:`add_section` is called with the name of a section
132    that is already present.
135 .. exception:: NoOptionError
137    Exception raised when a specified option is not found in the specified  section.
140 .. exception:: InterpolationError
142    Base class for exceptions raised when problems occur performing string
143    interpolation.
146 .. exception:: InterpolationDepthError
148    Exception raised when string interpolation cannot be completed because the
149    number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
150    :exc:`InterpolationError`.
153 .. exception:: InterpolationMissingOptionError
155    Exception raised when an option referenced from a value does not exist. Subclass
156    of :exc:`InterpolationError`.
158    .. versionadded:: 2.3
161 .. exception:: InterpolationSyntaxError
163    Exception raised when the source text into which substitutions are made does not
164    conform to the required syntax. Subclass of :exc:`InterpolationError`.
166    .. versionadded:: 2.3
169 .. exception:: MissingSectionHeaderError
171    Exception raised when attempting to parse a file which has no section headers.
174 .. exception:: ParsingError
176    Exception raised when errors occur attempting to parse a file.
179 .. data:: MAX_INTERPOLATION_DEPTH
181    The maximum depth for recursive interpolation for :meth:`get` when the *raw*
182    parameter is false.  This is relevant only for the :class:`ConfigParser` class.
185 .. seealso::
187    Module :mod:`shlex`
188       Support for a creating Unix shell-like mini-languages which can be used as an
189       alternate format for application configuration files.
192 .. _rawconfigparser-objects:
194 RawConfigParser Objects
195 -----------------------
197 :class:`RawConfigParser` instances have the following methods:
200 .. method:: RawConfigParser.defaults()
202    Return a dictionary containing the instance-wide defaults.
205 .. method:: RawConfigParser.sections()
207    Return a list of the sections available; ``DEFAULT`` is not included in the
208    list.
211 .. method:: RawConfigParser.add_section(section)
213    Add a section named *section* to the instance.  If a section by the given name
214    already exists, :exc:`DuplicateSectionError` is raised. If the name
215    ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
216    :exc:`ValueError` is raised.
218 .. method:: RawConfigParser.has_section(section)
220    Indicates whether the named section is present in the configuration. The
221    ``DEFAULT`` section is not acknowledged.
224 .. method:: RawConfigParser.options(section)
226    Returns a list of options available in the specified *section*.
229 .. method:: RawConfigParser.has_option(section, option)
231    If the given section exists, and contains the given option, return
232    :const:`True`; otherwise return :const:`False`.
234    .. versionadded:: 1.6
237 .. method:: RawConfigParser.read(filenames)
239    Attempt to read and parse a list of filenames, returning a list of filenames
240    which were successfully parsed.  If *filenames* is a string or Unicode string,
241    it is treated as a single filename. If a file named in *filenames* cannot be
242    opened, that file will be ignored.  This is designed so that you can specify a
243    list of potential configuration file locations (for example, the current
244    directory, the user's home directory, and some system-wide directory), and all
245    existing configuration files in the list will be read.  If none of the named
246    files exist, the :class:`ConfigParser` instance will contain an empty dataset.
247    An application which requires initial values to be loaded from a file should
248    load the required file or files using :meth:`readfp` before calling :meth:`read`
249    for any optional files::
251       import ConfigParser, os
253       config = ConfigParser.ConfigParser()
254       config.readfp(open('defaults.cfg'))
255       config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])
257    .. versionchanged:: 2.4
258       Returns list of successfully parsed filenames.
261 .. method:: RawConfigParser.readfp(fp[, filename])
263    Read and parse configuration data from the file or file-like object in *fp*
264    (only the :meth:`readline` method is used).  If *filename* is omitted and *fp*
265    has a :attr:`name` attribute, that is used for *filename*; the default is
266    ``<???>``.
269 .. method:: RawConfigParser.get(section, option)
271    Get an *option* value for the named *section*.
274 .. method:: RawConfigParser.getint(section, option)
276    A convenience method which coerces the *option* in the specified *section* to an
277    integer.
280 .. method:: RawConfigParser.getfloat(section, option)
282    A convenience method which coerces the *option* in the specified *section* to a
283    floating point number.
286 .. method:: RawConfigParser.getboolean(section, option)
288    A convenience method which coerces the *option* in the specified *section* to a
289    Boolean value.  Note that the accepted values for the option are ``"1"``,
290    ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
291    and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
292    ``False``.  These string values are checked in a case-insensitive manner.  Any
293    other value will cause it to raise :exc:`ValueError`.
296 .. method:: RawConfigParser.items(section)
298    Return a list of ``(name, value)`` pairs for each option in the given *section*.
301 .. method:: RawConfigParser.set(section, option, value)
303    If the given section exists, set the given option to the specified value;
304    otherwise raise :exc:`NoSectionError`.  While it is possible to use
305    :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to
306    true) for *internal* storage of non-string values, full functionality (including
307    interpolation and output to files) can only be achieved using string values.
309    .. versionadded:: 1.6
312 .. method:: RawConfigParser.write(fileobject)
314    Write a representation of the configuration to the specified file object.  This
315    representation can be parsed by a future :meth:`read` call.
317    .. versionadded:: 1.6
320 .. method:: RawConfigParser.remove_option(section, option)
322    Remove the specified *option* from the specified *section*. If the section does
323    not exist, raise :exc:`NoSectionError`.  If the option existed to be removed,
324    return :const:`True`; otherwise return :const:`False`.
326    .. versionadded:: 1.6
329 .. method:: RawConfigParser.remove_section(section)
331    Remove the specified *section* from the configuration. If the section in fact
332    existed, return ``True``. Otherwise return ``False``.
335 .. method:: RawConfigParser.optionxform(option)
337    Transforms the option name *option* as found in an input file or as passed in
338    by client code to the form that should be used in the internal structures.
339    The default implementation returns a lower-case version of *option*;
340    subclasses may override this or client code can set an attribute of this name
341    on instances to affect this behavior.
343    You don't necessarily need to subclass a ConfigParser to use this method, you
344    can also re-set it on an instance, to a function that takes a string
345    argument.  Setting it to ``str``, for example, would make option names case
346    sensitive::
348       cfgparser = ConfigParser()
349       ...
350       cfgparser.optionxform = str
352    Note that when reading configuration files, whitespace around the
353    option names are stripped before :meth:``optionxform`` is called.
356 .. _configparser-objects:
358 ConfigParser Objects
359 --------------------
361 The :class:`ConfigParser` class extends some methods of the
362 :class:`RawConfigParser` interface, adding some optional arguments.
365 .. method:: ConfigParser.get(section, option[, raw[, vars]])
367    Get an *option* value for the named *section*.  All the ``'%'`` interpolations
368    are expanded in the return values, based on the defaults passed into the
369    constructor, as well as the options *vars* provided, unless the *raw* argument
370    is true.
373 .. method:: ConfigParser.items(section[, raw[, vars]])
375    Return a list of ``(name, value)`` pairs for each option in the given *section*.
376    Optional arguments have the same meaning as for the :meth:`get` method.
378    .. versionadded:: 2.3
381 .. _safeconfigparser-objects:
383 SafeConfigParser Objects
384 ------------------------
386 The :class:`SafeConfigParser` class implements the same extended interface as
387 :class:`ConfigParser`, with the following addition:
390 .. method:: SafeConfigParser.set(section, option, value)
392    If the given section exists, set the given option to the specified value;
393    otherwise raise :exc:`NoSectionError`.  *value* must be a string (:class:`str`
394    or :class:`unicode`); if not, :exc:`TypeError` is raised.
396    .. versionadded:: 2.4
399 Examples
400 --------
402 An example of writing to a configuration file::
404    import ConfigParser
406    config = ConfigParser.RawConfigParser()
408    # When adding sections or items, add them in the reverse order of
409    # how you want them to be displayed in the actual file.
410    # In addition, please note that using RawConfigParser's and the raw
411    # mode of ConfigParser's respective set functions, you can assign
412    # non-string values to keys internally, but will receive an error
413    # when attempting to write to a file or when you get it in non-raw
414    # mode. SafeConfigParser does not allow such assignments to take place.
415    config.add_section('Section1')
416    config.set('Section1', 'int', '15')
417    config.set('Section1', 'bool', 'true')
418    config.set('Section1', 'float', '3.1415')
419    config.set('Section1', 'baz', 'fun')
420    config.set('Section1', 'bar', 'Python')
421    config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
423    # Writing our configuration file to 'example.cfg'
424    with open('example.cfg', 'wb') as configfile:
425        config.write(configfile)
427 An example of reading the configuration file again::
429    import ConfigParser
431    config = ConfigParser.RawConfigParser()
432    config.read('example.cfg')
434    # getfloat() raises an exception if the value is not a float
435    # getint() and getboolean() also do this for their respective types
436    float = config.getfloat('Section1', 'float')
437    int = config.getint('Section1', 'int')
438    print float + int
440    # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
441    # This is because we are using a RawConfigParser().
442    if config.getboolean('Section1', 'bool'):
443        print config.get('Section1', 'foo')
445 To get interpolation, you will need to use a :class:`ConfigParser` or
446 :class:`SafeConfigParser`::
448    import ConfigParser
450    config = ConfigParser.ConfigParser()
451    config.read('example.cfg')
453    # Set the third, optional argument of get to 1 if you wish to use raw mode.
454    print config.get('Section1', 'foo', 0) # -> "Python is fun!"
455    print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
457    # The optional fourth argument is a dict with members that will take
458    # precedence in interpolation.
459    print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
460                                            'baz': 'evil'})
462 Defaults are available in all three types of ConfigParsers. They are used in
463 interpolation if an option used is not defined elsewhere. ::
465    import ConfigParser
467    # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
468    config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
469    config.read('example.cfg')
471    print config.get('Section1', 'foo') # -> "Python is fun!"
472    config.remove_option('Section1', 'bar')
473    config.remove_option('Section1', 'baz')
474    print config.get('Section1', 'foo') # -> "Life is hard!"
476 The function ``opt_move`` below can be used to move options between sections::
478    def opt_move(config, section1, section2, option):
479        try:
480            config.set(section2, option, config.get(section1, option, 1))
481        except ConfigParser.NoSectionError:
482            # Create non-existent section
483            config.add_section(section2)
484            opt_move(config, section1, section2, option)
485        else:
486            config.remove_option(section1, option)