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