blob: d0b03f994779ca37f1c7c169be2280cb9343179b [file] [log] [blame]
Guido van Rossum3d209861997-12-09 16:10:31 +00001"""Configuration file parser.
2
3A setup file consists of sections, lead by a "[section]" header,
4and followed by "name: value" entries, with continuations and such in
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00005the style of RFC 822.
Guido van Rossum3d209861997-12-09 16:10:31 +00006
Barry Warsawbfa3f6b1998-07-01 20:41:12 +00007The option values can contain format strings which refer to other values in
8the same section, or values in a special [DEFAULT] section.
9
Guido van Rossum3d209861997-12-09 16:10:31 +000010For example:
11
12 something: %(dir)s/whatever
13
14would resolve the "%(dir)s" to the value of dir. All reference
15expansions are done late, on demand.
16
17Intrinsic defaults can be specified by passing them into the
18ConfigParser constructor as a dictionary.
19
20class:
21
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +000022ConfigParser -- responsible for parsing a list of
Guido van Rossum3d209861997-12-09 16:10:31 +000023 configuration files, and managing the parsed database.
24
25 methods:
26
Barry Warsawf09f6a51999-01-26 22:01:37 +000027 __init__(defaults=None)
28 create the parser and specify a dictionary of intrinsic defaults. The
29 keys must be strings, the values must be appropriate for %()s string
30 interpolation. Note that `__name__' is always an intrinsic default;
Georg Brandl7eb4b7d2005-07-22 21:49:32 +000031 its value is the section's name.
Guido van Rossum3d209861997-12-09 16:10:31 +000032
Barry Warsawf09f6a51999-01-26 22:01:37 +000033 sections()
34 return all the configuration section names, sans DEFAULT
Guido van Rossum3d209861997-12-09 16:10:31 +000035
Guido van Rossuma5a24b71999-10-04 19:58:22 +000036 has_section(section)
37 return whether the given section exists
38
Eric S. Raymond649685a2000-07-14 14:28:22 +000039 has_option(section, option)
40 return whether the given option exists in the given section
41
Barry Warsawf09f6a51999-01-26 22:01:37 +000042 options(section)
43 return list of configuration options for the named section
Guido van Rossum3d209861997-12-09 16:10:31 +000044
Guido van Rossumc0780ac1999-01-30 04:35:47 +000045 read(filenames)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000046 read and parse the list of named configuration files, given by
47 name. A single filename is also allowed. Non-existing files
Fred Drake82903142004-05-18 04:24:02 +000048 are ignored. Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +000049
50 readfp(fp, filename=None)
51 read and parse one configuration file, given as a file object.
52 The filename defaults to fp.name; it is only used in error
Barry Warsaw25394511999-10-12 16:12:48 +000053 messages (if fp has no `name' attribute, the string `<???>' is used).
Guido van Rossum3d209861997-12-09 16:10:31 +000054
Neal Norwitzf680cc42002-12-17 01:56:47 +000055 get(section, option, raw=False, vars=None)
Barry Warsawf09f6a51999-01-26 22:01:37 +000056 return a string value for the named option. All % interpolations are
57 expanded in the return values, based on the defaults passed into the
58 constructor and the DEFAULT section. Additional substitutions may be
59 provided using the `vars' argument, which must be a dictionary whose
60 contents override any pre-existing defaults.
Guido van Rossum3d209861997-12-09 16:10:31 +000061
Barry Warsawf09f6a51999-01-26 22:01:37 +000062 getint(section, options)
63 like get(), but convert value to an integer
Guido van Rossum3d209861997-12-09 16:10:31 +000064
Barry Warsawf09f6a51999-01-26 22:01:37 +000065 getfloat(section, options)
66 like get(), but convert value to a float
Guido van Rossum3d209861997-12-09 16:10:31 +000067
Barry Warsawf09f6a51999-01-26 22:01:37 +000068 getboolean(section, options)
Guido van Rossumfb06f752001-10-04 19:58:46 +000069 like get(), but convert value to a boolean (currently case
Neal Norwitzf680cc42002-12-17 01:56:47 +000070 insensitively defined as 0, false, no, off for False, and 1, true,
71 yes, on for True). Returns False or True.
Eric S. Raymond649685a2000-07-14 14:28:22 +000072
Neal Norwitzf680cc42002-12-17 01:56:47 +000073 items(section, raw=False, vars=None)
Fred Drake2ca041f2002-09-27 15:49:56 +000074 return a list of tuples with (name, value) for each option
75 in the section.
76
Eric S. Raymond649685a2000-07-14 14:28:22 +000077 remove_section(section)
Tim Peters88869f92001-01-14 23:36:06 +000078 remove the given file section and all its options
Eric S. Raymond649685a2000-07-14 14:28:22 +000079
80 remove_option(section, option)
Tim Peters88869f92001-01-14 23:36:06 +000081 remove the given option from the given section
Eric S. Raymond649685a2000-07-14 14:28:22 +000082
83 set(section, option, value)
84 set the given option
85
86 write(fp)
Tim Peters88869f92001-01-14 23:36:06 +000087 write the configuration state in .ini format
Guido van Rossum3d209861997-12-09 16:10:31 +000088"""
89
Raymond Hettingerff23e8c2009-03-03 01:32:48 +000090try:
91 from collections import OrderedDict as _default_dict
92except ImportError:
93 # fallback for setup.py which hasn't yet built _collections
94 _default_dict = dict
95
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000096import re
Guido van Rossum3d209861997-12-09 16:10:31 +000097
Fred Drake8d5dd982002-12-30 23:51:45 +000098__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
99 "InterpolationError", "InterpolationDepthError",
100 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +0000101 "MissingSectionHeaderError",
102 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +0000103 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +0000104
Guido van Rossum3d209861997-12-09 16:10:31 +0000105DEFAULTSECT = "DEFAULT"
106
Fred Drake2a37f9f2000-09-27 22:43:54 +0000107MAX_INTERPOLATION_DEPTH = 10
108
Guido van Rossum3d209861997-12-09 16:10:31 +0000109
Tim Peters88869f92001-01-14 23:36:06 +0000110
Guido van Rossum3d209861997-12-09 16:10:31 +0000111# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000112class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000113 """Base class for ConfigParser exceptions."""
114
Guido van Rossum360e4b82007-05-14 22:51:27 +0000115 def _get_message(self):
116 """Getter for 'message'; needed only to override deprecation in
117 BaseException."""
118 return self.__message
119
120 def _set_message(self, value):
121 """Setter for 'message'; needed only to override deprecation in
122 BaseException."""
123 self.__message = value
124
125 # BaseException.message has been deprecated since Python 2.6. To prevent
126 # DeprecationWarning from popping up over this pre-existing attribute, use
127 # a new property that takes lookup precedence.
128 message = property(_get_message, _set_message)
129
Guido van Rossum3d209861997-12-09 16:10:31 +0000130 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000131 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000132 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000133
Guido van Rossum3d209861997-12-09 16:10:31 +0000134 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000135 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000136
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000137 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000138
139class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000140 """Raised when no section matches a requested option."""
141
Guido van Rossum3d209861997-12-09 16:10:31 +0000142 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000143 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000145
146class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000147 """Raised when a section is multiply-created."""
148
Guido van Rossum3d209861997-12-09 16:10:31 +0000149 def __init__(self, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000150 Error.__init__(self, "Section %r already exists" % section)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000152
153class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000154 """A requested option was not found."""
155
Guido van Rossum3d209861997-12-09 16:10:31 +0000156 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000157 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000158 (option, section))
159 self.option = option
160 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000161
162class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000163 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000164
Fred Drakee2c64912002-12-31 17:23:27 +0000165 def __init__(self, option, section, msg):
166 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 self.option = option
168 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000169
Fred Drakee2c64912002-12-31 17:23:27 +0000170class InterpolationMissingOptionError(InterpolationError):
171 """A string substitution required a setting which was not available."""
172
173 def __init__(self, option, section, rawval, reference):
174 msg = ("Bad value substitution:\n"
175 "\tsection: [%s]\n"
176 "\toption : %s\n"
177 "\tkey : %s\n"
178 "\trawval : %s\n"
179 % (section, option, reference, rawval))
180 InterpolationError.__init__(self, option, section, msg)
181 self.reference = reference
182
183class InterpolationSyntaxError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000184 """Raised when the source text into which substitutions are made
185 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000186
Fred Drakee2c64912002-12-31 17:23:27 +0000187class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000188 """Raised when substitutions are nested too deeply."""
189
Fred Drake2a37f9f2000-09-27 22:43:54 +0000190 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000191 msg = ("Value interpolation too deeply recursive:\n"
192 "\tsection: [%s]\n"
193 "\toption : %s\n"
194 "\trawval : %s\n"
195 % (section, option, rawval))
196 InterpolationError.__init__(self, option, section, msg)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000197
198class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000199 """Raised when a configuration file does not follow legal syntax."""
200
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000201 def __init__(self, filename):
202 Error.__init__(self, 'File contains parsing errors: %s' % filename)
203 self.filename = filename
204 self.errors = []
205
206 def append(self, lineno, line):
207 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000208 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000209
Fred Drake2a37f9f2000-09-27 22:43:54 +0000210class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000211 """Raised when a key-value pair is found before any section header."""
212
Fred Drake2a37f9f2000-09-27 22:43:54 +0000213 def __init__(self, filename, lineno, line):
214 Error.__init__(
215 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000216 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000217 (filename, lineno, line))
218 self.filename = filename
219 self.lineno = lineno
220 self.line = line
221
Guido van Rossum3d209861997-12-09 16:10:31 +0000222
Fred Drakefce65572002-10-25 18:08:18 +0000223class RawConfigParser:
Fred Drake03c44a32010-02-19 06:08:41 +0000224 def __init__(self, defaults=None, dict_type=_default_dict,
225 allow_no_value=False):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000226 self._dict = dict_type
227 self._sections = self._dict()
228 self._defaults = self._dict()
Fred Drake03c44a32010-02-19 06:08:41 +0000229 if allow_no_value:
230 self._optcre = self.OPTCRE_NV
231 else:
232 self._optcre = self.OPTCRE
David Goodger68a1abd2004-10-03 15:40:25 +0000233 if defaults:
234 for key, value in defaults.items():
235 self._defaults[self.optionxform(key)] = value
Guido van Rossum3d209861997-12-09 16:10:31 +0000236
237 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000238 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000239
240 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000242 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000243 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000244
245 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000247
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 Raise DuplicateSectionError if a section by the specified name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000249 already exists. Raise ValueError if name is DEFAULT or any of it's
250 case-insensitive variants.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000251 """
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000252 if section.lower() == "default":
253 raise ValueError('Invalid section name: %s' % section)
254
Fred Drakefce65572002-10-25 18:08:18 +0000255 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257 self._sections[section] = self._dict()
Guido van Rossum3d209861997-12-09 16:10:31 +0000258
259 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000261
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000262 The DEFAULT section is not acknowledged.
263 """
Fred Drakefce65572002-10-25 18:08:18 +0000264 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000265
266 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000267 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000268 try:
Fred Drakefce65572002-10-25 18:08:18 +0000269 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000270 except KeyError:
271 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000272 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000273 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000274 del opts['__name__']
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000275 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000276
277 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000278 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000279
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000280 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000281 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000282 configuration file locations (e.g. current directory, user's
283 home directory, systemwide directory), and all existing
284 configuration files in the list will be read. A single
285 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000286
287 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000288 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000289 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000290 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000291 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000292 for filename in filenames:
293 try:
294 fp = open(filename)
295 except IOError:
296 continue
Fred Drakefce65572002-10-25 18:08:18 +0000297 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000298 fp.close()
Fred Drake82903142004-05-18 04:24:02 +0000299 read_ok.append(filename)
300 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000301
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000302 def readfp(self, fp, filename=None):
303 """Like read() but the argument must be a file-like object.
304
305 The `fp' argument must have a `readline' method. Optional
306 second argument is the `filename', which if not given, is
307 taken from fp.name. If fp has no `name' attribute, `<???>' is
308 used.
309
310 """
311 if filename is None:
312 try:
313 filename = fp.name
314 except AttributeError:
315 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000316 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000317
Fred Drakefce65572002-10-25 18:08:18 +0000318 def get(self, section, option):
319 opt = self.optionxform(option)
320 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000321 if section != DEFAULTSECT:
322 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000323 if opt in self._defaults:
324 return self._defaults[opt]
325 else:
326 raise NoOptionError(option, section)
327 elif opt in self._sections[section]:
328 return self._sections[section][opt]
329 elif opt in self._defaults:
330 return self._defaults[opt]
331 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000332 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000333
Fred Drakefce65572002-10-25 18:08:18 +0000334 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000335 try:
Fred Drakefce65572002-10-25 18:08:18 +0000336 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000337 except KeyError:
338 if section != DEFAULTSECT:
339 raise NoSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340 d2 = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000341 d = self._defaults.copy()
342 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000343 if "__name__" in d:
344 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000345 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000346
Fred Drakefce65572002-10-25 18:08:18 +0000347 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000348 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000349
350 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000351 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000352
353 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000354 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000355
Fred Drakec2ff9052002-09-27 15:33:11 +0000356 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
357 '0': False, 'no': False, 'false': False, 'off': False}
358
Guido van Rossum3d209861997-12-09 16:10:31 +0000359 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000360 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000361 if v.lower() not in self._boolean_states:
Collin Winterce36ad82007-08-30 01:19:48 +0000362 raise ValueError('Not a boolean: %s' % v)
Fred Drakec2ff9052002-09-27 15:33:11 +0000363 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000364
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000365 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000366 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000367
Eric S. Raymond417c4892000-07-10 18:11:00 +0000368 def has_option(self, section, option):
369 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000370 if not section or section == DEFAULTSECT:
371 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000372 return option in self._defaults
373 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000374 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000375 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000376 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000377 return (option in self._sections[section]
378 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000379
Fred Drake03c44a32010-02-19 06:08:41 +0000380 def set(self, section, option, value=None):
Eric S. Raymond417c4892000-07-10 18:11:00 +0000381 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000382 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000383 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000384 else:
385 try:
Fred Drakefce65572002-10-25 18:08:18 +0000386 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000387 except KeyError:
388 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000389 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000390
391 def write(self, fp):
392 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000393 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000394 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000395 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000396 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000397 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000398 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000399 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000400 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000401 if key != "__name__":
Fred Drake03c44a32010-02-19 06:08:41 +0000402 if value is None:
403 fp.write("%s\n" % (key))
404 else:
405 fp.write("%s = %s\n" %
406 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000407 fp.write("\n")
408
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000409 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000410 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000411 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000412 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000413 else:
414 try:
Fred Drakefce65572002-10-25 18:08:18 +0000415 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000416 except KeyError:
417 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000418 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000419 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000420 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000421 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000422 return existed
423
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000424 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000425 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000426 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000427 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000428 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000429 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000430
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000431 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000432 # Regular expressions for parsing section headers and options.
433 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000434 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000435 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000436 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000437 r'\]' # ]
438 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000439 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000440 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000441 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000442 # followed by separator
443 # (either : or =), followed
444 # by any # space/tab
445 r'(?P<value>.*)$' # everything up to eol
446 )
Fred Drake03c44a32010-02-19 06:08:41 +0000447 OPTCRE_NV = re.compile(
448 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
449 r'\s*(?:' # any number of space/tab,
450 r'(?P<vi>[:=])\s*' # optionally followed by
451 # separator (either : or
452 # =), followed by any #
453 # space/tab
454 r'(?P<value>.*))?$' # everything up to eol
455 )
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000456
Fred Drakefce65572002-10-25 18:08:18 +0000457 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000458 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000459
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000460 The sections in setup file contains a title line at the top,
461 indicated by a name in square brackets (`[]'), plus key/value
462 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000463 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000464 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000465 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000466 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000467 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000468 optname = None
469 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000470 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000471 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000472 line = fp.readline()
473 if not line:
474 break
475 lineno = lineno + 1
476 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000477 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000478 continue
Fred Drake176916a2002-09-27 16:21:18 +0000479 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
480 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000481 continue
482 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000483 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000484 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000485 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000486 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000487 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000488 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000489 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000490 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000491 if mo:
492 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000493 if sectname in self._sections:
494 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000495 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000496 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000497 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498 cursect = self._dict()
499 cursect['__name__'] = sectname
Fred Drakefce65572002-10-25 18:08:18 +0000500 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000501 # So sections can't start with a continuation line
502 optname = None
503 # no section header in the file?
504 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000505 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000506 # an option line?
507 else:
Fred Drake03c44a32010-02-19 06:08:41 +0000508 mo = self._optcre.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000509 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000510 optname, vi, optval = mo.group('option', 'vi', 'value')
Fred Drake03c44a32010-02-19 06:08:41 +0000511 # This check is fine because the OPTCRE cannot
512 # match if it would set optval to None
513 if optval is not None:
514 if vi in ('=', ':') and ';' in optval:
515 # ';' is a comment delimiter only if it follows
516 # a spacing character
517 pos = optval.find(';')
518 if pos != -1 and optval[pos-1].isspace():
519 optval = optval[:pos]
520 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000521 # allow empty values
522 if optval == '""':
523 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000524 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000525 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000526 else:
527 # a non-fatal parsing error occurred. set up the
528 # exception but keep going. the exception will be
529 # raised at the end of the file and will contain a
530 # list of all bogus lines
531 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000532 e = ParsingError(fpname)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000533 e.append(lineno, repr(line))
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000534 # if any parsing errors occurred, raise an exception
535 if e:
536 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000537
538
539class ConfigParser(RawConfigParser):
540
Neal Norwitzf680cc42002-12-17 01:56:47 +0000541 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000542 """Get an option value for a given section.
543
544 All % interpolations are expanded in the return values, based on the
545 defaults passed into the constructor, unless the optional argument
546 `raw' is true. Additional substitutions may be provided using the
547 `vars' argument, which must be a dictionary whose contents overrides
548 any pre-existing defaults.
549
550 The section DEFAULT is special.
551 """
552 d = self._defaults.copy()
553 try:
554 d.update(self._sections[section])
555 except KeyError:
556 if section != DEFAULTSECT:
557 raise NoSectionError(section)
558 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +0000559 if vars:
560 for key, value in vars.items():
561 d[self.optionxform(key)] = value
Fred Drakefce65572002-10-25 18:08:18 +0000562 option = self.optionxform(option)
563 try:
564 value = d[option]
565 except KeyError:
566 raise NoOptionError(option, section)
567
Fred Drake03c44a32010-02-19 06:08:41 +0000568 if raw or value is None:
Fred Drakefce65572002-10-25 18:08:18 +0000569 return value
570 else:
571 return self._interpolate(section, option, value, d)
572
Neal Norwitzf680cc42002-12-17 01:56:47 +0000573 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000574 """Return a list of tuples with (name, value) for each option
575 in the section.
576
577 All % interpolations are expanded in the return values, based on the
578 defaults passed into the constructor, unless the optional argument
579 `raw' is true. Additional substitutions may be provided using the
580 `vars' argument, which must be a dictionary whose contents overrides
581 any pre-existing defaults.
582
583 The section DEFAULT is special.
584 """
585 d = self._defaults.copy()
586 try:
587 d.update(self._sections[section])
588 except KeyError:
589 if section != DEFAULTSECT:
590 raise NoSectionError(section)
591 # Update with the entry specific variables
592 if vars:
David Goodger68a1abd2004-10-03 15:40:25 +0000593 for key, value in vars.items():
594 d[self.optionxform(key)] = value
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000595 options = list(d.keys())
Fred Drakedf393bd2002-10-25 20:41:30 +0000596 if "__name__" in options:
597 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000598 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +0000599 return [(option, d[option])
600 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000601 else:
Fred Drake8c4da532003-10-21 16:45:00 +0000602 return [(option, self._interpolate(section, option, d[option], d))
603 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000604
605 def _interpolate(self, section, option, rawval, vars):
606 # do the string interpolation
607 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000608 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000609 while depth: # Loop through this until it's done
610 depth -= 1
Fred Drake03c44a32010-02-19 06:08:41 +0000611 if value and "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +0000612 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +0000613 try:
614 value = value % vars
Guido van Rossumb940e112007-01-10 16:19:56 +0000615 except KeyError as e:
Fred Drakee2c64912002-12-31 17:23:27 +0000616 raise InterpolationMissingOptionError(
Brett Cannonca477b22007-03-21 22:26:20 +0000617 option, section, rawval, e.args[0])
Fred Drakefce65572002-10-25 18:08:18 +0000618 else:
619 break
Fred Drake03c44a32010-02-19 06:08:41 +0000620 if value and "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +0000621 raise InterpolationDepthError(option, section, rawval)
622 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000623
Fred Drakebc12b012004-05-18 02:25:51 +0000624 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
625
626 def _interpolation_replace(self, match):
627 s = match.group(1)
628 if s is None:
629 return match.group()
630 else:
631 return "%%(%s)s" % self.optionxform(s)
632
Fred Drake0eebd5c2002-10-25 21:52:00 +0000633
634class SafeConfigParser(ConfigParser):
635
636 def _interpolate(self, section, option, rawval, vars):
637 # do the string interpolation
638 L = []
639 self._interpolate_some(option, L, rawval, section, vars, 1)
640 return ''.join(L)
641
Guido van Rossumd8faa362007-04-27 19:54:29 +0000642 _interpvar_re = re.compile(r"%\(([^)]+)\)s")
Fred Drake0eebd5c2002-10-25 21:52:00 +0000643
644 def _interpolate_some(self, option, accum, rest, section, map, depth):
645 if depth > MAX_INTERPOLATION_DEPTH:
646 raise InterpolationDepthError(option, section, rest)
647 while rest:
648 p = rest.find("%")
649 if p < 0:
650 accum.append(rest)
651 return
652 if p > 0:
653 accum.append(rest[:p])
654 rest = rest[p:]
655 # p is no longer used
656 c = rest[1:2]
657 if c == "%":
658 accum.append("%")
659 rest = rest[2:]
660 elif c == "(":
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661 m = self._interpvar_re.match(rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000662 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +0000663 raise InterpolationSyntaxError(option, section,
664 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +0000665 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +0000666 rest = rest[m.end():]
667 try:
668 v = map[var]
669 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +0000670 raise InterpolationMissingOptionError(
671 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000672 if "%" in v:
673 self._interpolate_some(option, accum, v,
674 section, map, depth + 1)
675 else:
676 accum.append(v)
677 else:
678 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +0000679 option, section,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000680 "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +0000681
Fred Drake03c44a32010-02-19 06:08:41 +0000682 def set(self, section, option, value=None):
David Goodger1cbf2062004-10-03 15:55:09 +0000683 """Set an option. Extend ConfigParser.set: check for string values."""
Fred Drake03c44a32010-02-19 06:08:41 +0000684 # The only legal non-string value if we allow valueless
685 # options is None, so we need to check if the value is a
686 # string if:
687 # - we do not allow valueless options, or
688 # - we allow valueless options but the value is not None
689 if self._optcre is self.OPTCRE or value:
690 if not isinstance(value, str):
691 raise TypeError("option values must be strings")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000692 # check for bad percent signs:
693 # first, replace all "good" interpolations
Georg Brandl68998bf2009-04-27 16:43:36 +0000694 tmp_value = value.replace('%%', '')
695 tmp_value = self._interpvar_re.sub('', tmp_value)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000696 # then, check if there's a lone percent sign left
Georg Brandl1f9fa312009-04-27 16:42:58 +0000697 percent_index = tmp_value.find('%')
698 if percent_index != -1:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699 raise ValueError("invalid interpolation syntax in %r at "
Georg Brandl1f9fa312009-04-27 16:42:58 +0000700 "position %d" % (value, percent_index))
David Goodger1cbf2062004-10-03 15:55:09 +0000701 ConfigParser.set(self, section, option, value)