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