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