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