Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 1 | :mod:`ConfigParser` --- Configuration file parser |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 2 | ================================================= |
| 3 | |
Alexandre Vassalotti | c92fef9 | 2008-05-14 22:51:10 +0000 | [diff] [blame] | 4 | .. module:: ConfigParser |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 5 | :synopsis: Configuration file parser. |
Alexandre Vassalotti | e2514c6 | 2008-05-14 22:44:22 +0000 | [diff] [blame] | 6 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +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 | |
Alexandre Vassalotti | c92fef9 | 2008-05-14 22:51:10 +0000 | [diff] [blame] | 12 | .. note:: |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 13 | |
Georg Brandl | e92818f | 2009-01-03 20:47:01 +0000 | [diff] [blame] | 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. |
Alexandre Vassalotti | c92fef9 | 2008-05-14 22:51:10 +0000 | [diff] [blame] | 17 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 16a57f6 | 2009-04-27 15:29:09 +0000 | [diff] [blame] | 30 | .. note:: |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 31 | |
Georg Brandl | 16a57f6 | 2009-04-27 15:29:09 +0000 | [diff] [blame] | 32 | This library does *not* interpret or write the value-type prefixes used in |
| 33 | the Windows Registry extended version of INI syntax. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 |
Georg Brandl | 27f4374 | 2008-03-26 09:32:46 +0000 | [diff] [blame] | 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. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 43 | |
| 44 | For example:: |
| 45 | |
| 46 | [My Section] |
| 47 | foodir: %(dir)s/whatever |
| 48 | dir=frob |
Georg Brandl | 27f4374 | 2008-03-26 09:32:46 +0000 | [diff] [blame] | 49 | long: this value continues |
| 50 | in the next line |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 | |
Georg Brandl | d7d4fd7 | 2009-07-26 14:37:28 +0000 | [diff] [blame] | 59 | Sections are normally stored in a built-in dictionary. An alternative dictionary |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 | |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 65 | .. class:: RawConfigParser([defaults[, dict_type[, allow_no_value]]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 70 | options within a section, and for the default values. When *allow_no_value* |
| 71 | is true (default: ``False``), options without values are accepted; the value |
| 72 | presented for these is ``None``. |
| 73 | |
| 74 | This class does not |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 75 | support the magical interpolation behavior. |
| 76 | |
| 77 | .. versionadded:: 2.3 |
| 78 | |
| 79 | .. versionchanged:: 2.6 |
| 80 | *dict_type* was added. |
| 81 | |
Raymond Hettinger | e89b8e9 | 2009-03-03 05:00:37 +0000 | [diff] [blame] | 82 | .. versionchanged:: 2.7 |
| 83 | The default *dict_type* is :class:`collections.OrderedDict`. |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 84 | *allow_no_value* was added. |
Raymond Hettinger | e89b8e9 | 2009-03-03 05:00:37 +0000 | [diff] [blame] | 85 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 86 | |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 87 | .. class:: ConfigParser([defaults[, dict_type[, allow_no_value]]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 88 | |
| 89 | Derived class of :class:`RawConfigParser` that implements the magical |
| 90 | interpolation feature and adds optional arguments to the :meth:`get` and |
| 91 | :meth:`items` methods. The values in *defaults* must be appropriate for the |
| 92 | ``%()s`` string interpolation. Note that *__name__* is an intrinsic default; |
| 93 | its value is the section name, and will override any value provided in |
| 94 | *defaults*. |
| 95 | |
| 96 | All option names used in interpolation will be passed through the |
| 97 | :meth:`optionxform` method just like any other option name reference. For |
| 98 | example, using the default implementation of :meth:`optionxform` (which converts |
| 99 | option names to lower case), the values ``foo %(bar)s`` and ``foo %(BAR)s`` are |
| 100 | equivalent. |
| 101 | |
Raymond Hettinger | e89b8e9 | 2009-03-03 05:00:37 +0000 | [diff] [blame] | 102 | .. versionadded:: 2.3 |
| 103 | |
| 104 | .. versionchanged:: 2.6 |
| 105 | *dict_type* was added. |
| 106 | |
| 107 | .. versionchanged:: 2.7 |
| 108 | The default *dict_type* is :class:`collections.OrderedDict`. |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 109 | *allow_no_value* was added. |
Raymond Hettinger | e89b8e9 | 2009-03-03 05:00:37 +0000 | [diff] [blame] | 110 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 111 | |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 112 | .. class:: SafeConfigParser([defaults[, dict_type[, allow_no_value]]]) |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 113 | |
| 114 | Derived class of :class:`ConfigParser` that implements a more-sane variant of |
| 115 | the magical interpolation feature. This implementation is more predictable as |
| 116 | well. New applications should prefer this version if they don't need to be |
| 117 | compatible with older versions of Python. |
| 118 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 119 | .. XXX Need to explain what's safer/more predictable about it. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 120 | |
| 121 | .. versionadded:: 2.3 |
| 122 | |
Raymond Hettinger | e89b8e9 | 2009-03-03 05:00:37 +0000 | [diff] [blame] | 123 | .. versionchanged:: 2.6 |
| 124 | *dict_type* was added. |
| 125 | |
| 126 | .. versionchanged:: 2.7 |
| 127 | The default *dict_type* is :class:`collections.OrderedDict`. |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 128 | *allow_no_value* was added. |
Raymond Hettinger | e89b8e9 | 2009-03-03 05:00:37 +0000 | [diff] [blame] | 129 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 130 | |
| 131 | .. exception:: NoSectionError |
| 132 | |
| 133 | Exception raised when a specified section is not found. |
| 134 | |
| 135 | |
| 136 | .. exception:: DuplicateSectionError |
| 137 | |
| 138 | Exception raised if :meth:`add_section` is called with the name of a section |
| 139 | that is already present. |
| 140 | |
| 141 | |
| 142 | .. exception:: NoOptionError |
| 143 | |
| 144 | Exception raised when a specified option is not found in the specified section. |
| 145 | |
| 146 | |
| 147 | .. exception:: InterpolationError |
| 148 | |
| 149 | Base class for exceptions raised when problems occur performing string |
| 150 | interpolation. |
| 151 | |
| 152 | |
| 153 | .. exception:: InterpolationDepthError |
| 154 | |
| 155 | Exception raised when string interpolation cannot be completed because the |
| 156 | number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of |
| 157 | :exc:`InterpolationError`. |
| 158 | |
| 159 | |
| 160 | .. exception:: InterpolationMissingOptionError |
| 161 | |
| 162 | Exception raised when an option referenced from a value does not exist. Subclass |
| 163 | of :exc:`InterpolationError`. |
| 164 | |
| 165 | .. versionadded:: 2.3 |
| 166 | |
| 167 | |
| 168 | .. exception:: InterpolationSyntaxError |
| 169 | |
| 170 | Exception raised when the source text into which substitutions are made does not |
| 171 | conform to the required syntax. Subclass of :exc:`InterpolationError`. |
| 172 | |
| 173 | .. versionadded:: 2.3 |
| 174 | |
| 175 | |
| 176 | .. exception:: MissingSectionHeaderError |
| 177 | |
| 178 | Exception raised when attempting to parse a file which has no section headers. |
| 179 | |
| 180 | |
| 181 | .. exception:: ParsingError |
| 182 | |
| 183 | Exception raised when errors occur attempting to parse a file. |
| 184 | |
| 185 | |
| 186 | .. data:: MAX_INTERPOLATION_DEPTH |
| 187 | |
| 188 | The maximum depth for recursive interpolation for :meth:`get` when the *raw* |
| 189 | parameter is false. This is relevant only for the :class:`ConfigParser` class. |
| 190 | |
| 191 | |
| 192 | .. seealso:: |
| 193 | |
| 194 | Module :mod:`shlex` |
| 195 | Support for a creating Unix shell-like mini-languages which can be used as an |
| 196 | alternate format for application configuration files. |
| 197 | |
| 198 | |
| 199 | .. _rawconfigparser-objects: |
| 200 | |
| 201 | RawConfigParser Objects |
| 202 | ----------------------- |
| 203 | |
| 204 | :class:`RawConfigParser` instances have the following methods: |
| 205 | |
| 206 | |
| 207 | .. method:: RawConfigParser.defaults() |
| 208 | |
| 209 | Return a dictionary containing the instance-wide defaults. |
| 210 | |
| 211 | |
| 212 | .. method:: RawConfigParser.sections() |
| 213 | |
| 214 | Return a list of the sections available; ``DEFAULT`` is not included in the |
| 215 | list. |
| 216 | |
| 217 | |
| 218 | .. method:: RawConfigParser.add_section(section) |
| 219 | |
| 220 | Add a section named *section* to the instance. If a section by the given name |
Facundo Batista | b12f0b5 | 2008-02-23 12:46:10 +0000 | [diff] [blame] | 221 | already exists, :exc:`DuplicateSectionError` is raised. If the name |
| 222 | ``DEFAULT`` (or any of it's case-insensitive variants) is passed, |
| 223 | :exc:`ValueError` is raised. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 224 | |
| 225 | .. method:: RawConfigParser.has_section(section) |
| 226 | |
| 227 | Indicates whether the named section is present in the configuration. The |
| 228 | ``DEFAULT`` section is not acknowledged. |
| 229 | |
| 230 | |
| 231 | .. method:: RawConfigParser.options(section) |
| 232 | |
| 233 | Returns a list of options available in the specified *section*. |
| 234 | |
| 235 | |
| 236 | .. method:: RawConfigParser.has_option(section, option) |
| 237 | |
| 238 | If the given section exists, and contains the given option, return |
| 239 | :const:`True`; otherwise return :const:`False`. |
| 240 | |
| 241 | .. versionadded:: 1.6 |
| 242 | |
| 243 | |
| 244 | .. method:: RawConfigParser.read(filenames) |
| 245 | |
| 246 | Attempt to read and parse a list of filenames, returning a list of filenames |
| 247 | which were successfully parsed. If *filenames* is a string or Unicode string, |
| 248 | it is treated as a single filename. If a file named in *filenames* cannot be |
| 249 | opened, that file will be ignored. This is designed so that you can specify a |
| 250 | list of potential configuration file locations (for example, the current |
| 251 | directory, the user's home directory, and some system-wide directory), and all |
| 252 | existing configuration files in the list will be read. If none of the named |
| 253 | files exist, the :class:`ConfigParser` instance will contain an empty dataset. |
| 254 | An application which requires initial values to be loaded from a file should |
| 255 | load the required file or files using :meth:`readfp` before calling :meth:`read` |
| 256 | for any optional files:: |
| 257 | |
Benjamin Peterson | a7b55a3 | 2009-02-20 03:31:23 +0000 | [diff] [blame] | 258 | import ConfigParser, os |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 259 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 260 | config = ConfigParser.ConfigParser() |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 261 | config.readfp(open('defaults.cfg')) |
| 262 | config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')]) |
| 263 | |
| 264 | .. versionchanged:: 2.4 |
| 265 | Returns list of successfully parsed filenames. |
| 266 | |
| 267 | |
| 268 | .. method:: RawConfigParser.readfp(fp[, filename]) |
| 269 | |
| 270 | Read and parse configuration data from the file or file-like object in *fp* |
| 271 | (only the :meth:`readline` method is used). If *filename* is omitted and *fp* |
| 272 | has a :attr:`name` attribute, that is used for *filename*; the default is |
| 273 | ``<???>``. |
| 274 | |
| 275 | |
| 276 | .. method:: RawConfigParser.get(section, option) |
| 277 | |
| 278 | Get an *option* value for the named *section*. |
| 279 | |
| 280 | |
| 281 | .. method:: RawConfigParser.getint(section, option) |
| 282 | |
| 283 | A convenience method which coerces the *option* in the specified *section* to an |
| 284 | integer. |
| 285 | |
| 286 | |
| 287 | .. method:: RawConfigParser.getfloat(section, option) |
| 288 | |
| 289 | A convenience method which coerces the *option* in the specified *section* to a |
| 290 | floating point number. |
| 291 | |
| 292 | |
| 293 | .. method:: RawConfigParser.getboolean(section, option) |
| 294 | |
| 295 | A convenience method which coerces the *option* in the specified *section* to a |
| 296 | Boolean value. Note that the accepted values for the option are ``"1"``, |
| 297 | ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``, |
| 298 | and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return |
| 299 | ``False``. These string values are checked in a case-insensitive manner. Any |
| 300 | other value will cause it to raise :exc:`ValueError`. |
| 301 | |
| 302 | |
| 303 | .. method:: RawConfigParser.items(section) |
| 304 | |
| 305 | Return a list of ``(name, value)`` pairs for each option in the given *section*. |
| 306 | |
| 307 | |
| 308 | .. method:: RawConfigParser.set(section, option, value) |
| 309 | |
| 310 | If the given section exists, set the given option to the specified value; |
| 311 | otherwise raise :exc:`NoSectionError`. While it is possible to use |
| 312 | :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to |
| 313 | true) for *internal* storage of non-string values, full functionality (including |
| 314 | interpolation and output to files) can only be achieved using string values. |
| 315 | |
| 316 | .. versionadded:: 1.6 |
| 317 | |
| 318 | |
| 319 | .. method:: RawConfigParser.write(fileobject) |
| 320 | |
| 321 | Write a representation of the configuration to the specified file object. This |
| 322 | representation can be parsed by a future :meth:`read` call. |
| 323 | |
| 324 | .. versionadded:: 1.6 |
| 325 | |
| 326 | |
| 327 | .. method:: RawConfigParser.remove_option(section, option) |
| 328 | |
| 329 | Remove the specified *option* from the specified *section*. If the section does |
| 330 | not exist, raise :exc:`NoSectionError`. If the option existed to be removed, |
| 331 | return :const:`True`; otherwise return :const:`False`. |
| 332 | |
| 333 | .. versionadded:: 1.6 |
| 334 | |
| 335 | |
| 336 | .. method:: RawConfigParser.remove_section(section) |
| 337 | |
| 338 | Remove the specified *section* from the configuration. If the section in fact |
| 339 | existed, return ``True``. Otherwise return ``False``. |
| 340 | |
| 341 | |
| 342 | .. method:: RawConfigParser.optionxform(option) |
| 343 | |
Georg Brandl | dc02052 | 2009-10-23 08:14:44 +0000 | [diff] [blame] | 344 | Transforms the option name *option* as found in an input file or as passed in |
| 345 | by client code to the form that should be used in the internal structures. |
| 346 | The default implementation returns a lower-case version of *option*; |
| 347 | subclasses may override this or client code can set an attribute of this name |
| 348 | on instances to affect this behavior. |
| 349 | |
| 350 | You don't necessarily need to subclass a ConfigParser to use this method, you |
| 351 | can also re-set it on an instance, to a function that takes a string |
| 352 | argument. Setting it to ``str``, for example, would make option names case |
| 353 | sensitive:: |
| 354 | |
| 355 | cfgparser = ConfigParser() |
| 356 | ... |
| 357 | cfgparser.optionxform = str |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 358 | |
Fred Drake | d617cba | 2009-10-23 13:04:51 +0000 | [diff] [blame] | 359 | Note that when reading configuration files, whitespace around the |
Georg Brandl | 5460ff9 | 2009-10-24 10:04:19 +0000 | [diff] [blame] | 360 | option names are stripped before :meth:`optionxform` is called. |
Fred Drake | d617cba | 2009-10-23 13:04:51 +0000 | [diff] [blame] | 361 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 362 | |
| 363 | .. _configparser-objects: |
| 364 | |
| 365 | ConfigParser Objects |
| 366 | -------------------- |
| 367 | |
| 368 | The :class:`ConfigParser` class extends some methods of the |
| 369 | :class:`RawConfigParser` interface, adding some optional arguments. |
| 370 | |
| 371 | |
| 372 | .. method:: ConfigParser.get(section, option[, raw[, vars]]) |
| 373 | |
| 374 | Get an *option* value for the named *section*. All the ``'%'`` interpolations |
| 375 | are expanded in the return values, based on the defaults passed into the |
| 376 | constructor, as well as the options *vars* provided, unless the *raw* argument |
| 377 | is true. |
| 378 | |
| 379 | |
| 380 | .. method:: ConfigParser.items(section[, raw[, vars]]) |
| 381 | |
| 382 | Return a list of ``(name, value)`` pairs for each option in the given *section*. |
| 383 | Optional arguments have the same meaning as for the :meth:`get` method. |
| 384 | |
| 385 | .. versionadded:: 2.3 |
| 386 | |
| 387 | |
| 388 | .. _safeconfigparser-objects: |
| 389 | |
| 390 | SafeConfigParser Objects |
| 391 | ------------------------ |
| 392 | |
| 393 | The :class:`SafeConfigParser` class implements the same extended interface as |
| 394 | :class:`ConfigParser`, with the following addition: |
| 395 | |
| 396 | |
| 397 | .. method:: SafeConfigParser.set(section, option, value) |
| 398 | |
| 399 | If the given section exists, set the given option to the specified value; |
| 400 | otherwise raise :exc:`NoSectionError`. *value* must be a string (:class:`str` |
| 401 | or :class:`unicode`); if not, :exc:`TypeError` is raised. |
| 402 | |
| 403 | .. versionadded:: 2.4 |
| 404 | |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 405 | |
| 406 | Examples |
| 407 | -------- |
| 408 | |
| 409 | An example of writing to a configuration file:: |
| 410 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 411 | import ConfigParser |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 412 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 413 | config = ConfigParser.RawConfigParser() |
| 414 | |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 415 | # When adding sections or items, add them in the reverse order of |
| 416 | # how you want them to be displayed in the actual file. |
| 417 | # In addition, please note that using RawConfigParser's and the raw |
| 418 | # mode of ConfigParser's respective set functions, you can assign |
| 419 | # non-string values to keys internally, but will receive an error |
| 420 | # when attempting to write to a file or when you get it in non-raw |
| 421 | # mode. SafeConfigParser does not allow such assignments to take place. |
| 422 | config.add_section('Section1') |
| 423 | config.set('Section1', 'int', '15') |
| 424 | config.set('Section1', 'bool', 'true') |
| 425 | config.set('Section1', 'float', '3.1415') |
| 426 | config.set('Section1', 'baz', 'fun') |
| 427 | config.set('Section1', 'bar', 'Python') |
| 428 | config.set('Section1', 'foo', '%(bar)s is %(baz)s!') |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 429 | |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 430 | # Writing our configuration file to 'example.cfg' |
| 431 | with open('example.cfg', 'wb') as configfile: |
| 432 | config.write(configfile) |
| 433 | |
| 434 | An example of reading the configuration file again:: |
| 435 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 436 | import ConfigParser |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 437 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 438 | config = ConfigParser.RawConfigParser() |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 439 | config.read('example.cfg') |
| 440 | |
| 441 | # getfloat() raises an exception if the value is not a float |
| 442 | # getint() and getboolean() also do this for their respective types |
| 443 | float = config.getfloat('Section1', 'float') |
| 444 | int = config.getint('Section1', 'int') |
| 445 | print float + int |
| 446 | |
| 447 | # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. |
| 448 | # This is because we are using a RawConfigParser(). |
| 449 | if config.getboolean('Section1', 'bool'): |
| 450 | print config.get('Section1', 'foo') |
| 451 | |
| 452 | To get interpolation, you will need to use a :class:`ConfigParser` or |
| 453 | :class:`SafeConfigParser`:: |
| 454 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 455 | import ConfigParser |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 456 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 457 | config = ConfigParser.ConfigParser() |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 458 | config.read('example.cfg') |
| 459 | |
| 460 | # Set the third, optional argument of get to 1 if you wish to use raw mode. |
| 461 | print config.get('Section1', 'foo', 0) # -> "Python is fun!" |
| 462 | print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!" |
| 463 | |
| 464 | # The optional fourth argument is a dict with members that will take |
| 465 | # precedence in interpolation. |
| 466 | print config.get('Section1', 'foo', 0, {'bar': 'Documentation', |
| 467 | 'baz': 'evil'}) |
| 468 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 469 | Defaults are available in all three types of ConfigParsers. They are used in |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 470 | interpolation if an option used is not defined elsewhere. :: |
| 471 | |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 472 | import ConfigParser |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 473 | |
| 474 | # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 475 | config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'}) |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 476 | config.read('example.cfg') |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 477 | |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 478 | print config.get('Section1', 'foo') # -> "Python is fun!" |
| 479 | config.remove_option('Section1', 'bar') |
| 480 | config.remove_option('Section1', 'baz') |
| 481 | print config.get('Section1', 'foo') # -> "Life is hard!" |
| 482 | |
| 483 | The function ``opt_move`` below can be used to move options between sections:: |
| 484 | |
| 485 | def opt_move(config, section1, section2, option): |
| 486 | try: |
| 487 | config.set(section2, option, config.get(section1, option, 1)) |
Georg Brandl | 392c6fc | 2008-05-25 07:25:25 +0000 | [diff] [blame] | 488 | except ConfigParser.NoSectionError: |
Georg Brandl | 430e362 | 2007-11-29 17:02:34 +0000 | [diff] [blame] | 489 | # Create non-existent section |
| 490 | config.add_section(section2) |
| 491 | opt_move(config, section1, section2, option) |
Georg Brandl | 960b186 | 2008-01-21 16:28:13 +0000 | [diff] [blame] | 492 | else: |
| 493 | config.remove_option(section1, option) |
Fred Drake | cc43b56 | 2010-02-19 05:24:30 +0000 | [diff] [blame^] | 494 | |
| 495 | Some configuration files are known to include settings without values, but which |
| 496 | otherwise conform to the syntax supported by :mod:`ConfigParser`. The |
| 497 | *allow_no_value* parameter to the constructor can be used to indicate that such |
| 498 | values should be accepted: |
| 499 | |
| 500 | .. doctest:: |
| 501 | |
| 502 | >>> import ConfigParser |
| 503 | >>> import io |
| 504 | |
| 505 | >>> sample_config = """ |
| 506 | ... [mysqld] |
| 507 | ... user = mysql |
| 508 | ... pid-file = /var/run/mysqld/mysqld.pid |
| 509 | ... skip-external-locking |
| 510 | ... old_passwords = 1 |
| 511 | ... skip-bdb |
| 512 | ... skip-innodb |
| 513 | ... """ |
| 514 | >>> config = ConfigParser.RawConfigParser(allow_no_value=True) |
| 515 | >>> config.readfp(io.BytesIO(sample_config)) |
| 516 | |
| 517 | >>> # Settings with values are treated as before: |
| 518 | >>> config.get("mysqld", "user") |
| 519 | 'mysql' |
| 520 | |
| 521 | >>> # Settings without values provide None: |
| 522 | >>> config.get("mysqld", "skip-bdb") |
| 523 | |
| 524 | >>> # Settings which aren't specified still raise an error: |
| 525 | >>> config.get("mysqld", "does-not-exist") |
| 526 | Traceback (most recent call last): |
| 527 | ... |
| 528 | ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld' |