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