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 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 18 | This module provides the classes :class:`RawConfigParser` and |
| 19 | :class:`SafeConfigParser`. They implement a basic configuration file parser |
| 20 | language which provides a structure similar to what you would find in Microsoft |
| 21 | Windows INI files. You can use this to write Python programs which can be |
| 22 | customized by end users easily. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 29 | A configuration file consists of sections, each led by a ``[section]`` header, |
| 30 | followed by name/value entries separated by a specific string (``=`` or ``:`` by |
| 31 | default). Note that leading whitespace is removed from values. Values can be |
| 32 | ommitted, in which case the key/value delimiter may also be left out. Values |
| 33 | can also span multiple lines, as long as they are indented deeper than the first |
| 34 | line of the value. Depending on the parser's mode, blank lines may be treated |
| 35 | as parts of multiline values or ignored. |
| 36 | |
| 37 | Configuration files may include comments, prefixed by specific characters (``#`` |
| 38 | and ``;`` by default). Comments may appear on their own in an otherwise empty |
| 39 | line, or may be entered in lines holding values or spection names. In the |
| 40 | latter case, they need to be preceded by a whitespace character to be recognized |
| 41 | as a comment. (For backwards compatibility, by default only ``;`` starts an |
| 42 | inline comment, while ``#`` does not.) |
| 43 | |
| 44 | On top of the core functionality, :class:`SafeConfigParser` supports |
| 45 | interpolation. This means values can contain format strings which refer to |
| 46 | other values in the same section, or values in a special ``DEFAULT`` section. |
Georg Brandl | 470a123 | 2010-07-29 14:17:12 +0000 | [diff] [blame] | 47 | Additional defaults can be provided on initialization. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 48 | |
| 49 | For example:: |
| 50 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 51 | [Paths] |
| 52 | home_dir: /Users |
| 53 | my_dir: %(home_dir)s/lumberjack |
| 54 | my_pictures: %(my_dir)s/Pictures |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 55 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 56 | [Multiline Values] |
| 57 | chorus: I'm a lumberjack, and I'm okay |
| 58 | I sleep all night and I work all day |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 59 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 60 | [No Values] |
| 61 | key_without_value |
| 62 | empty string value here = |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 63 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 64 | [You can use comments] ; after a useful line |
| 65 | ; in an empty line |
| 66 | after: a_value ; here's another comment |
| 67 | inside: a ;comment |
| 68 | multiline ;comment |
| 69 | value! ;comment |
| 70 | |
| 71 | [Sections Can Be Indented] |
| 72 | can_values_be_as_well = True |
| 73 | does_that_mean_anything_special = False |
| 74 | purpose = formatting for readability |
| 75 | multiline_values = are |
| 76 | handled just fine as |
| 77 | long as they are indented |
| 78 | deeper than the first line |
| 79 | of a value |
| 80 | # Did I mention we can indent comments, too? |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 81 | |
| 82 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 83 | In the example above, :class:`SafeConfigParser` would resolve ``%(home_dir)s`` |
| 84 | to the value of ``home_dir`` (``/Users`` in this case). ``%(my_dir)s`` in |
| 85 | effect would resolve to ``/Users/lumberjack``. All interpolations are done on |
| 86 | demand so keys used in the chain of references do not have to be specified in |
| 87 | any specific order in the configuration file. |
| 88 | |
| 89 | :class:`RawConfigParser` would simply return ``%(my_dir)s/Pictures`` as the |
| 90 | value of ``my_pictures`` and ``%(home_dir)s/lumberjack`` as the value of |
| 91 | ``my_dir``. Other features presented in the example are handled in the same |
| 92 | manner by both parsers. |
| 93 | |
| 94 | Default values can be specified by passing them as a dictionary when |
Georg Brandl | 470a123 | 2010-07-29 14:17:12 +0000 | [diff] [blame] | 95 | constructing the :class:`SafeConfigParser`. |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 96 | |
| 97 | Sections are normally stored in an :class:`collections.OrderedDict` which |
| 98 | maintains the order of all keys. An alternative dictionary type can be passed |
| 99 | to the :meth:`__init__` method. For example, if a dictionary type is passed |
| 100 | that sorts its keys, the sections will be sorted on write-back, as will be the |
| 101 | keys within each section. |
| 102 | |
| 103 | |
| 104 | .. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, empty_lines_in_values=True, allow_no_value=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 105 | |
| 106 | The basic configuration object. When *defaults* is given, it is initialized |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 107 | into the dictionary of intrinsic defaults. When *dict_type* is given, it |
| 108 | will be used to create the dictionary objects for the list of sections, for |
| 109 | the options within a section, and for the default values. |
| 110 | |
| 111 | When *delimiters* is given, it will be used as the set of substrings that |
| 112 | divide keys from values. When *comment_prefixes* is given, it will be used |
| 113 | as the set of substrings that prefix comments in a line, both for the whole |
| 114 | line and inline comments. For backwards compatibility, the default value for |
| 115 | *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can |
| 116 | start whole line comments while only ``;`` can start inline comments. |
| 117 | |
| 118 | When *empty_lines_in_values* is ``False`` (default: ``True``), each empty |
| 119 | line marks the end of an option. Otherwise, internal empty lines of a |
| 120 | multiline option are kept as part of the value. When *allow_no_value* is |
| 121 | true (default: ``False``), options without values are accepted; the value |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 122 | presented for these is ``None``. |
| 123 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 124 | This class does not support the magical interpolation behavior. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 125 | |
Raymond Hettinger | 231b7f1 | 2009-03-03 00:23:19 +0000 | [diff] [blame] | 126 | .. versionchanged:: 3.1 |
Raymond Hettinger | 0663a1e | 2009-03-02 23:06:00 +0000 | [diff] [blame] | 127 | The default *dict_type* is :class:`collections.OrderedDict`. |
| 128 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 129 | .. versionchanged:: 3.2 |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 130 | *delimiters*, *comment_prefixes*, *empty_lines_in_values* and |
| 131 | *allow_no_value* were added. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 132 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 133 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 134 | .. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=('#', ';'), empty_lines_in_values=True, allow_no_value=False) |
| 135 | |
| 136 | Derived class of :class:`ConfigParser` that implements a sane variant of the |
| 137 | magical interpolation feature. This implementation is more predictable as it |
| 138 | validates the interpolation syntax used within a configuration file. This |
| 139 | class also enables escaping the interpolation character (e.g. a key can have |
| 140 | ``%`` as part of the value by specifying ``%%`` in the file). |
| 141 | |
| 142 | Applications that don't require interpolation should use |
| 143 | :class:`RawConfigParser`, otherwise :class:`SafeConfigParser` is the best |
| 144 | option. |
| 145 | |
| 146 | .. versionchanged:: 3.1 |
| 147 | The default *dict_type* is :class:`collections.OrderedDict`. |
| 148 | |
| 149 | .. versionchanged:: 3.2 |
| 150 | *delimiters*, *comment_prefixes*, *empty_lines_in_values* and |
| 151 | *allow_no_value* were added. |
| 152 | |
| 153 | |
| 154 | .. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, delimiters=('=', ':'), comment_prefixes=('#', ';'), empty_lines_in_values=True, allow_no_value=False) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 155 | |
| 156 | Derived class of :class:`RawConfigParser` that implements the magical |
| 157 | interpolation feature and adds optional arguments to the :meth:`get` and |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 158 | :meth:`items` methods. |
| 159 | |
| 160 | :class:`SafeConfigParser` is generally recommended over this class if you |
| 161 | need interpolation. |
| 162 | |
| 163 | The values in *defaults* must be appropriate for the ``%()s`` string |
| 164 | interpolation. Note that *__name__* is an intrinsic default; its value is |
| 165 | the section name, and will override any value provided in *defaults*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 166 | |
| 167 | All option names used in interpolation will be passed through the |
| 168 | :meth:`optionxform` method just like any other option name reference. For |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 169 | example, using the default implementation of :meth:`optionxform` (which |
| 170 | converts option names to lower case), the values ``foo %(bar)s`` and ``foo |
| 171 | %(BAR)s`` are equivalent. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 172 | |
Raymond Hettinger | 231b7f1 | 2009-03-03 00:23:19 +0000 | [diff] [blame] | 173 | .. versionchanged:: 3.1 |
Raymond Hettinger | 0663a1e | 2009-03-02 23:06:00 +0000 | [diff] [blame] | 174 | The default *dict_type* is :class:`collections.OrderedDict`. |
| 175 | |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 176 | .. versionchanged:: 3.2 |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 177 | *delimiters*, *comment_prefixes*, *empty_lines_in_values* and |
| 178 | *allow_no_value* were added. |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 179 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 180 | |
Georg Brandl | 436ccdc | 2010-07-29 14:32:22 +0000 | [diff] [blame] | 181 | .. exception:: Error |
| 182 | |
| 183 | Base class for all other configparser exceptions. |
| 184 | |
| 185 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 186 | .. exception:: NoSectionError |
| 187 | |
| 188 | Exception raised when a specified section is not found. |
| 189 | |
| 190 | |
| 191 | .. exception:: DuplicateSectionError |
| 192 | |
| 193 | Exception raised if :meth:`add_section` is called with the name of a section |
| 194 | that is already present. |
| 195 | |
| 196 | |
| 197 | .. exception:: NoOptionError |
| 198 | |
| 199 | Exception raised when a specified option is not found in the specified section. |
| 200 | |
| 201 | |
| 202 | .. exception:: InterpolationError |
| 203 | |
| 204 | Base class for exceptions raised when problems occur performing string |
| 205 | interpolation. |
| 206 | |
| 207 | |
| 208 | .. exception:: InterpolationDepthError |
| 209 | |
| 210 | Exception raised when string interpolation cannot be completed because the |
| 211 | number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of |
| 212 | :exc:`InterpolationError`. |
| 213 | |
| 214 | |
| 215 | .. exception:: InterpolationMissingOptionError |
| 216 | |
| 217 | Exception raised when an option referenced from a value does not exist. Subclass |
| 218 | of :exc:`InterpolationError`. |
| 219 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 220 | |
| 221 | .. exception:: InterpolationSyntaxError |
| 222 | |
| 223 | Exception raised when the source text into which substitutions are made does not |
| 224 | conform to the required syntax. Subclass of :exc:`InterpolationError`. |
| 225 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 226 | |
| 227 | .. exception:: MissingSectionHeaderError |
| 228 | |
| 229 | Exception raised when attempting to parse a file which has no section headers. |
| 230 | |
| 231 | |
| 232 | .. exception:: ParsingError |
| 233 | |
| 234 | Exception raised when errors occur attempting to parse a file. |
| 235 | |
| 236 | |
| 237 | .. data:: MAX_INTERPOLATION_DEPTH |
| 238 | |
| 239 | The maximum depth for recursive interpolation for :meth:`get` when the *raw* |
| 240 | parameter is false. This is relevant only for the :class:`ConfigParser` class. |
| 241 | |
| 242 | |
| 243 | .. seealso:: |
| 244 | |
| 245 | Module :mod:`shlex` |
| 246 | Support for a creating Unix shell-like mini-languages which can be used as an |
| 247 | alternate format for application configuration files. |
| 248 | |
| 249 | |
| 250 | .. _rawconfigparser-objects: |
| 251 | |
| 252 | RawConfigParser Objects |
| 253 | ----------------------- |
| 254 | |
| 255 | :class:`RawConfigParser` instances have the following methods: |
| 256 | |
| 257 | |
| 258 | .. method:: RawConfigParser.defaults() |
| 259 | |
| 260 | Return a dictionary containing the instance-wide defaults. |
| 261 | |
| 262 | |
| 263 | .. method:: RawConfigParser.sections() |
| 264 | |
| 265 | Return a list of the sections available; ``DEFAULT`` is not included in the |
| 266 | list. |
| 267 | |
| 268 | |
| 269 | .. method:: RawConfigParser.add_section(section) |
| 270 | |
| 271 | 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] | 272 | already exists, :exc:`DuplicateSectionError` is raised. If the name |
| 273 | ``DEFAULT`` (or any of it's case-insensitive variants) is passed, |
| 274 | :exc:`ValueError` is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 275 | |
| 276 | .. method:: RawConfigParser.has_section(section) |
| 277 | |
| 278 | Indicates whether the named section is present in the configuration. The |
| 279 | ``DEFAULT`` section is not acknowledged. |
| 280 | |
| 281 | |
| 282 | .. method:: RawConfigParser.options(section) |
| 283 | |
| 284 | Returns a list of options available in the specified *section*. |
| 285 | |
| 286 | |
| 287 | .. method:: RawConfigParser.has_option(section, option) |
| 288 | |
| 289 | If the given section exists, and contains the given option, return |
| 290 | :const:`True`; otherwise return :const:`False`. |
| 291 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 292 | |
Georg Brandl | 8dcaa73 | 2010-07-29 12:17:40 +0000 | [diff] [blame] | 293 | .. method:: RawConfigParser.read(filenames, encoding=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 294 | |
| 295 | Attempt to read and parse a list of filenames, returning a list of filenames |
Georg Brandl | 8dcaa73 | 2010-07-29 12:17:40 +0000 | [diff] [blame] | 296 | which were successfully parsed. If *filenames* is a string, it is treated as |
| 297 | a single filename. If a file named in *filenames* cannot be opened, that |
| 298 | file will be ignored. This is designed so that you can specify a list of |
| 299 | potential configuration file locations (for example, the current directory, |
| 300 | the user's home directory, and some system-wide directory), and all existing |
| 301 | configuration files in the list will be read. If none of the named files |
| 302 | exist, the :class:`ConfigParser` instance will contain an empty dataset. An |
| 303 | application which requires initial values to be loaded from a file should |
| 304 | load the required file or files using :meth:`readfp` before calling |
| 305 | :meth:`read` for any optional files:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 306 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 307 | import configparser, os |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 308 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 309 | config = configparser.ConfigParser() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 310 | config.readfp(open('defaults.cfg')) |
Georg Brandl | 8dcaa73 | 2010-07-29 12:17:40 +0000 | [diff] [blame] | 311 | config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250') |
| 312 | |
| 313 | .. versionadded:: 3.2 |
| 314 | The *encoding* parameter. Previously, all files were read using the |
| 315 | default encoding for :func:`open`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 316 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 317 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 318 | .. method:: RawConfigParser.readfp(fp, filename=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 319 | |
| 320 | 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] | 321 | (only the :meth:`readline` method is used). The file-like object must |
| 322 | operate in text mode, i.e. return strings from :meth:`readline`. |
| 323 | |
| 324 | If *filename* is omitted and *fp* has a :attr:`name` attribute, that is used |
| 325 | for *filename*; the default is ``<???>``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 326 | |
| 327 | |
| 328 | .. method:: RawConfigParser.get(section, option) |
| 329 | |
| 330 | Get an *option* value for the named *section*. |
| 331 | |
| 332 | |
| 333 | .. method:: RawConfigParser.getint(section, option) |
| 334 | |
| 335 | A convenience method which coerces the *option* in the specified *section* to an |
| 336 | integer. |
| 337 | |
| 338 | |
| 339 | .. method:: RawConfigParser.getfloat(section, option) |
| 340 | |
| 341 | A convenience method which coerces the *option* in the specified *section* to a |
| 342 | floating point number. |
| 343 | |
| 344 | |
| 345 | .. method:: RawConfigParser.getboolean(section, option) |
| 346 | |
| 347 | A convenience method which coerces the *option* in the specified *section* to a |
| 348 | Boolean value. Note that the accepted values for the option are ``"1"``, |
| 349 | ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``, |
| 350 | and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return |
| 351 | ``False``. These string values are checked in a case-insensitive manner. Any |
| 352 | other value will cause it to raise :exc:`ValueError`. |
| 353 | |
| 354 | |
| 355 | .. method:: RawConfigParser.items(section) |
| 356 | |
| 357 | Return a list of ``(name, value)`` pairs for each option in the given *section*. |
| 358 | |
| 359 | |
| 360 | .. method:: RawConfigParser.set(section, option, value) |
| 361 | |
| 362 | If the given section exists, set the given option to the specified value; |
| 363 | otherwise raise :exc:`NoSectionError`. While it is possible to use |
| 364 | :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set to |
| 365 | true) for *internal* storage of non-string values, full functionality (including |
| 366 | interpolation and output to files) can only be achieved using string values. |
| 367 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 368 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 369 | .. method:: RawConfigParser.write(fileobject, space_around_delimiters=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 370 | |
Georg Brandl | 73753d3 | 2009-09-22 13:53:14 +0000 | [diff] [blame] | 371 | Write a representation of the configuration to the specified file object, |
| 372 | which must be opened in text mode (accepting strings). This representation |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 373 | can be parsed by a future :meth:`read` call. If ``space_around_delimiters`` |
| 374 | is ``True`` (the default), delimiters between keys and values are surrounded |
| 375 | by spaces. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 376 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 377 | |
| 378 | .. method:: RawConfigParser.remove_option(section, option) |
| 379 | |
| 380 | Remove the specified *option* from the specified *section*. If the section does |
| 381 | not exist, raise :exc:`NoSectionError`. If the option existed to be removed, |
| 382 | return :const:`True`; otherwise return :const:`False`. |
| 383 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 384 | |
| 385 | .. method:: RawConfigParser.remove_section(section) |
| 386 | |
| 387 | Remove the specified *section* from the configuration. If the section in fact |
| 388 | existed, return ``True``. Otherwise return ``False``. |
| 389 | |
| 390 | |
| 391 | .. method:: RawConfigParser.optionxform(option) |
| 392 | |
Georg Brandl | 495f7b5 | 2009-10-27 15:28:25 +0000 | [diff] [blame] | 393 | Transforms the option name *option* as found in an input file or as passed in |
| 394 | by client code to the form that should be used in the internal structures. |
| 395 | The default implementation returns a lower-case version of *option*; |
| 396 | subclasses may override this or client code can set an attribute of this name |
| 397 | on instances to affect this behavior. |
| 398 | |
| 399 | You don't necessarily need to subclass a ConfigParser to use this method, you |
| 400 | can also re-set it on an instance, to a function that takes a string |
| 401 | argument. Setting it to ``str``, for example, would make option names case |
| 402 | sensitive:: |
| 403 | |
| 404 | cfgparser = ConfigParser() |
| 405 | ... |
| 406 | cfgparser.optionxform = str |
| 407 | |
| 408 | Note that when reading configuration files, whitespace around the |
| 409 | option names are stripped before :meth:`optionxform` is called. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 410 | |
| 411 | |
| 412 | .. _configparser-objects: |
| 413 | |
| 414 | ConfigParser Objects |
| 415 | -------------------- |
| 416 | |
| 417 | The :class:`ConfigParser` class extends some methods of the |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 418 | :class:`RawConfigParser` interface, adding some optional arguments. Whenever you |
| 419 | can, consider using :class:`SafeConfigParser` which adds validation and escaping |
| 420 | for the interpolation. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 421 | |
| 422 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 423 | .. method:: ConfigParser.get(section, option, raw=False, vars=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 424 | |
Georg Brandl | 470a123 | 2010-07-29 14:17:12 +0000 | [diff] [blame] | 425 | Get an *option* value for the named *section*. If *vars* is provided, it |
| 426 | must be a dictionary. The *option* is looked up in *vars* (if provided), |
| 427 | *section*, and in *defaults* in that order. |
| 428 | |
| 429 | All the ``'%'`` interpolations are expanded in the return values, unless the |
| 430 | *raw* argument is true. Values for interpolation keys are looked up in the |
| 431 | same manner as the option. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | |
| 433 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 434 | .. method:: ConfigParser.items(section, raw=False, vars=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 435 | |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 436 | Return a list of ``(name, value)`` pairs for each option in the given |
| 437 | *section*. Optional arguments have the same meaning as for the :meth:`get` |
| 438 | method. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 439 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 440 | |
| 441 | .. _safeconfigparser-objects: |
| 442 | |
| 443 | SafeConfigParser Objects |
| 444 | ------------------------ |
| 445 | |
| 446 | The :class:`SafeConfigParser` class implements the same extended interface as |
| 447 | :class:`ConfigParser`, with the following addition: |
| 448 | |
| 449 | |
| 450 | .. method:: SafeConfigParser.set(section, option, value) |
| 451 | |
| 452 | 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] | 453 | otherwise raise :exc:`NoSectionError`. *value* must be a string; if it is |
| 454 | not, :exc:`TypeError` is raised. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 455 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 456 | |
| 457 | Examples |
| 458 | -------- |
| 459 | |
| 460 | An example of writing to a configuration file:: |
| 461 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 462 | import configparser |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 463 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 464 | config = configparser.RawConfigParser() |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 465 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 466 | # When adding sections or items, add them in the reverse order of |
| 467 | # how you want them to be displayed in the actual file. |
| 468 | # In addition, please note that using RawConfigParser's and the raw |
| 469 | # mode of ConfigParser's respective set functions, you can assign |
| 470 | # non-string values to keys internally, but will receive an error |
| 471 | # when attempting to write to a file or when you get it in non-raw |
| 472 | # mode. SafeConfigParser does not allow such assignments to take place. |
| 473 | config.add_section('Section1') |
| 474 | config.set('Section1', 'int', '15') |
| 475 | config.set('Section1', 'bool', 'true') |
| 476 | config.set('Section1', 'float', '3.1415') |
| 477 | config.set('Section1', 'baz', 'fun') |
| 478 | config.set('Section1', 'bar', 'Python') |
| 479 | config.set('Section1', 'foo', '%(bar)s is %(baz)s!') |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 480 | |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 481 | # Writing our configuration file to 'example.cfg' |
Georg Brandl | 73753d3 | 2009-09-22 13:53:14 +0000 | [diff] [blame] | 482 | with open('example.cfg', 'w') as configfile: |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 483 | config.write(configfile) |
| 484 | |
| 485 | An example of reading the configuration file again:: |
| 486 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 487 | import configparser |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 488 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 489 | config = configparser.RawConfigParser() |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 490 | config.read('example.cfg') |
| 491 | |
| 492 | # getfloat() raises an exception if the value is not a float |
| 493 | # getint() and getboolean() also do this for their respective types |
| 494 | float = config.getfloat('Section1', 'float') |
| 495 | int = config.getint('Section1', 'int') |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 496 | print(float + int) |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 497 | |
| 498 | # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'. |
| 499 | # This is because we are using a RawConfigParser(). |
| 500 | if config.getboolean('Section1', 'bool'): |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 501 | print(config.get('Section1', 'foo')) |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 502 | |
| 503 | To get interpolation, you will need to use a :class:`ConfigParser` or |
| 504 | :class:`SafeConfigParser`:: |
| 505 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 506 | import configparser |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 507 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 508 | config = configparser.ConfigParser() |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 509 | config.read('example.cfg') |
| 510 | |
| 511 | # 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] | 512 | print(config.get('Section1', 'foo', 0)) # -> "Python is fun!" |
| 513 | print(config.get('Section1', 'foo', 1)) # -> "%(bar)s is %(baz)s!" |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 514 | |
| 515 | # The optional fourth argument is a dict with members that will take |
| 516 | # precedence in interpolation. |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 517 | print(config.get('Section1', 'foo', 0, {'bar': 'Documentation', |
| 518 | 'baz': 'evil'})) |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 519 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 520 | 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] | 521 | interpolation if an option used is not defined elsewhere. :: |
| 522 | |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 523 | import configparser |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 524 | |
| 525 | # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 526 | config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'}) |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 527 | config.read('example.cfg') |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 528 | |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 529 | print(config.get('Section1', 'foo')) # -> "Python is fun!" |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 530 | config.remove_option('Section1', 'bar') |
| 531 | config.remove_option('Section1', 'baz') |
Georg Brandl | f694518 | 2008-02-01 11:56:49 +0000 | [diff] [blame] | 532 | print(config.get('Section1', 'foo')) # -> "Life is hard!" |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 533 | |
| 534 | The function ``opt_move`` below can be used to move options between sections:: |
| 535 | |
| 536 | def opt_move(config, section1, section2, option): |
| 537 | try: |
| 538 | config.set(section2, option, config.get(section1, option, 1)) |
Alexandre Vassalotti | 1d1eaa4 | 2008-05-14 22:59:42 +0000 | [diff] [blame] | 539 | except configparser.NoSectionError: |
Guido van Rossum | 2fd4f37 | 2007-11-29 18:43:05 +0000 | [diff] [blame] | 540 | # Create non-existent section |
| 541 | config.add_section(section2) |
| 542 | opt_move(config, section1, section2, option) |
Georg Brandl | 86def6c | 2008-01-21 20:36:10 +0000 | [diff] [blame] | 543 | else: |
| 544 | config.remove_option(section1, option) |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 545 | |
| 546 | Some configuration files are known to include settings without values, but which |
| 547 | otherwise conform to the syntax supported by :mod:`configparser`. The |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 548 | *allow_no_value* parameter to the :meth:`__init__` method can be used to |
| 549 | indicate that such values should be accepted: |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 550 | |
| 551 | .. doctest:: |
| 552 | |
| 553 | >>> import configparser |
| 554 | >>> import io |
| 555 | |
| 556 | >>> sample_config = """ |
| 557 | ... [mysqld] |
Georg Brandl | 96a60ae | 2010-07-28 13:13:46 +0000 | [diff] [blame] | 558 | ... user = mysql |
| 559 | ... pid-file = /var/run/mysqld/mysqld.pid |
| 560 | ... skip-external-locking |
| 561 | ... old_passwords = 1 |
| 562 | ... skip-bdb |
| 563 | ... skip-innodb # we don't need ACID today |
Fred Drake | 03c44a3 | 2010-02-19 06:08:41 +0000 | [diff] [blame] | 564 | ... """ |
| 565 | >>> config = configparser.RawConfigParser(allow_no_value=True) |
| 566 | >>> config.readfp(io.BytesIO(sample_config)) |
| 567 | |
| 568 | >>> # Settings with values are treated as before: |
| 569 | >>> config.get("mysqld", "user") |
| 570 | 'mysql' |
| 571 | |
| 572 | >>> # Settings without values provide None: |
| 573 | >>> config.get("mysqld", "skip-bdb") |
| 574 | |
| 575 | >>> # Settings which aren't specified still raise an error: |
| 576 | >>> config.get("mysqld", "does-not-exist") |
| 577 | Traceback (most recent call last): |
| 578 | ... |
| 579 | configparser.NoOptionError: No option 'does-not-exist' in section: 'mysqld' |