blob: f2e644c1add0bf7748997ae91850166e803bd636 [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
Barry Warsawbfa3f6b1998-07-01 20:41:12 +000090import re
Raymond Hettinger0663a1e2009-03-02 23:06:00 +000091from collections import OrderedDict
Guido van Rossum3d209861997-12-09 16:10:31 +000092
Fred Drake8d5dd982002-12-30 23:51:45 +000093__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
94 "InterpolationError", "InterpolationDepthError",
95 "InterpolationSyntaxError", "ParsingError",
David Goodger1cbf2062004-10-03 15:55:09 +000096 "MissingSectionHeaderError",
97 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000098 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000099
Guido van Rossum3d209861997-12-09 16:10:31 +0000100DEFAULTSECT = "DEFAULT"
101
Fred Drake2a37f9f2000-09-27 22:43:54 +0000102MAX_INTERPOLATION_DEPTH = 10
103
Guido van Rossum3d209861997-12-09 16:10:31 +0000104
Tim Peters88869f92001-01-14 23:36:06 +0000105
Guido van Rossum3d209861997-12-09 16:10:31 +0000106# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000107class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000108 """Base class for ConfigParser exceptions."""
109
Guido van Rossum360e4b82007-05-14 22:51:27 +0000110 def _get_message(self):
111 """Getter for 'message'; needed only to override deprecation in
112 BaseException."""
113 return self.__message
114
115 def _set_message(self, value):
116 """Setter for 'message'; needed only to override deprecation in
117 BaseException."""
118 self.__message = value
119
120 # BaseException.message has been deprecated since Python 2.6. To prevent
121 # DeprecationWarning from popping up over this pre-existing attribute, use
122 # a new property that takes lookup precedence.
123 message = property(_get_message, _set_message)
124
Guido van Rossum3d209861997-12-09 16:10:31 +0000125 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000126 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000127 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000128
Guido van Rossum3d209861997-12-09 16:10:31 +0000129 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000130 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000131
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000132 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000133
134class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000135 """Raised when no section matches a requested option."""
136
Guido van Rossum3d209861997-12-09 16:10:31 +0000137 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000138 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000139 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000140
141class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000142 """Raised when a section is multiply-created."""
143
Guido van Rossum3d209861997-12-09 16:10:31 +0000144 def __init__(self, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000145 Error.__init__(self, "Section %r already exists" % section)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000146 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000147
148class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000149 """A requested option was not found."""
150
Guido van Rossum3d209861997-12-09 16:10:31 +0000151 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000152 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000153 (option, section))
154 self.option = option
155 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000156
157class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000158 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000159
Fred Drakee2c64912002-12-31 17:23:27 +0000160 def __init__(self, option, section, msg):
161 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000162 self.option = option
163 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000164
Fred Drakee2c64912002-12-31 17:23:27 +0000165class InterpolationMissingOptionError(InterpolationError):
166 """A string substitution required a setting which was not available."""
167
168 def __init__(self, option, section, rawval, reference):
169 msg = ("Bad value substitution:\n"
170 "\tsection: [%s]\n"
171 "\toption : %s\n"
172 "\tkey : %s\n"
173 "\trawval : %s\n"
174 % (section, option, reference, rawval))
175 InterpolationError.__init__(self, option, section, msg)
176 self.reference = reference
177
178class InterpolationSyntaxError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000179 """Raised when the source text into which substitutions are made
180 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000181
Fred Drakee2c64912002-12-31 17:23:27 +0000182class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000183 """Raised when substitutions are nested too deeply."""
184
Fred Drake2a37f9f2000-09-27 22:43:54 +0000185 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000186 msg = ("Value interpolation too deeply recursive:\n"
187 "\tsection: [%s]\n"
188 "\toption : %s\n"
189 "\trawval : %s\n"
190 % (section, option, rawval))
191 InterpolationError.__init__(self, option, section, msg)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000192
193class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000194 """Raised when a configuration file does not follow legal syntax."""
195
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000196 def __init__(self, filename):
197 Error.__init__(self, 'File contains parsing errors: %s' % filename)
198 self.filename = filename
199 self.errors = []
200
201 def append(self, lineno, line):
202 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000203 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000204
Fred Drake2a37f9f2000-09-27 22:43:54 +0000205class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000206 """Raised when a key-value pair is found before any section header."""
207
Fred Drake2a37f9f2000-09-27 22:43:54 +0000208 def __init__(self, filename, lineno, line):
209 Error.__init__(
210 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000211 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000212 (filename, lineno, line))
213 self.filename = filename
214 self.lineno = lineno
215 self.line = line
216
Guido van Rossum3d209861997-12-09 16:10:31 +0000217
Fred Drakefce65572002-10-25 18:08:18 +0000218class RawConfigParser:
Raymond Hettinger0663a1e2009-03-02 23:06:00 +0000219 def __init__(self, defaults=None, dict_type=OrderedDict):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000220 self._dict = dict_type
221 self._sections = self._dict()
222 self._defaults = self._dict()
David Goodger68a1abd2004-10-03 15:40:25 +0000223 if defaults:
224 for key, value in defaults.items():
225 self._defaults[self.optionxform(key)] = value
Guido van Rossum3d209861997-12-09 16:10:31 +0000226
227 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000228 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000229
230 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000231 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000232 # self._sections will never have [DEFAULT] in it
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000233 return list(self._sections.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000234
235 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000236 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000237
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000238 Raise DuplicateSectionError if a section by the specified name
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000239 already exists. Raise ValueError if name is DEFAULT or any of it's
240 case-insensitive variants.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 """
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000242 if section.lower() == "default":
243 raise ValueError('Invalid section name: %s' % section)
244
Fred Drakefce65572002-10-25 18:08:18 +0000245 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 raise DuplicateSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000247 self._sections[section] = self._dict()
Guido van Rossum3d209861997-12-09 16:10:31 +0000248
249 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000250 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000251
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 The DEFAULT section is not acknowledged.
253 """
Fred Drakefce65572002-10-25 18:08:18 +0000254 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000255
256 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000257 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000258 try:
Fred Drakefce65572002-10-25 18:08:18 +0000259 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 except KeyError:
261 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000262 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000263 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000264 del opts['__name__']
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000265 return list(opts.keys())
Guido van Rossum3d209861997-12-09 16:10:31 +0000266
267 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000268 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000269
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000270 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000271 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000272 configuration file locations (e.g. current directory, user's
273 home directory, systemwide directory), and all existing
274 configuration files in the list will be read. A single
275 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000276
277 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000278 """
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000279 if isinstance(filenames, str):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000280 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000281 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000282 for filename in filenames:
283 try:
284 fp = open(filename)
285 except IOError:
286 continue
Fred Drakefce65572002-10-25 18:08:18 +0000287 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000288 fp.close()
Fred Drake82903142004-05-18 04:24:02 +0000289 read_ok.append(filename)
290 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000291
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000292 def readfp(self, fp, filename=None):
293 """Like read() but the argument must be a file-like object.
294
295 The `fp' argument must have a `readline' method. Optional
296 second argument is the `filename', which if not given, is
297 taken from fp.name. If fp has no `name' attribute, `<???>' is
298 used.
299
300 """
301 if filename is None:
302 try:
303 filename = fp.name
304 except AttributeError:
305 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000306 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000307
Fred Drakefce65572002-10-25 18:08:18 +0000308 def get(self, section, option):
309 opt = self.optionxform(option)
310 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000311 if section != DEFAULTSECT:
312 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000313 if opt in self._defaults:
314 return self._defaults[opt]
315 else:
316 raise NoOptionError(option, section)
317 elif opt in self._sections[section]:
318 return self._sections[section][opt]
319 elif opt in self._defaults:
320 return self._defaults[opt]
321 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000322 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000323
Fred Drakefce65572002-10-25 18:08:18 +0000324 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000325 try:
Fred Drakefce65572002-10-25 18:08:18 +0000326 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000327 except KeyError:
328 if section != DEFAULTSECT:
329 raise NoSectionError(section)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000330 d2 = self._dict()
Fred Drakefce65572002-10-25 18:08:18 +0000331 d = self._defaults.copy()
332 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000333 if "__name__" in d:
334 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000335 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000336
Fred Drakefce65572002-10-25 18:08:18 +0000337 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000338 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000339
340 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000341 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000342
343 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000344 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000345
Fred Drakec2ff9052002-09-27 15:33:11 +0000346 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
347 '0': False, 'no': False, 'false': False, 'off': False}
348
Guido van Rossum3d209861997-12-09 16:10:31 +0000349 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000350 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000351 if v.lower() not in self._boolean_states:
Collin Winterce36ad82007-08-30 01:19:48 +0000352 raise ValueError('Not a boolean: %s' % v)
Fred Drakec2ff9052002-09-27 15:33:11 +0000353 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000354
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000355 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000356 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000357
Eric S. Raymond417c4892000-07-10 18:11:00 +0000358 def has_option(self, section, option):
359 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000360 if not section or section == DEFAULTSECT:
361 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000362 return option in self._defaults
363 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000364 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000365 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000366 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000367 return (option in self._sections[section]
368 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000369
370 def set(self, section, option, value):
371 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000372 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000373 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000374 else:
375 try:
Fred Drakefce65572002-10-25 18:08:18 +0000376 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000377 except KeyError:
378 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000379 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000380
381 def write(self, fp):
382 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000383 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000384 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000385 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000386 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000387 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000388 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000389 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000390 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000391 if key != "__name__":
392 fp.write("%s = %s\n" %
393 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000394 fp.write("\n")
395
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000396 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000397 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000398 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000399 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000400 else:
401 try:
Fred Drakefce65572002-10-25 18:08:18 +0000402 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000403 except KeyError:
404 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000405 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000406 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000407 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000408 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000409 return existed
410
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000411 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000412 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000413 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000414 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000415 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000416 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000417
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000418 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000419 # Regular expressions for parsing section headers and options.
420 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000421 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000422 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000423 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000424 r'\]' # ]
425 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000426 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000427 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000428 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000429 # followed by separator
430 # (either : or =), followed
431 # by any # space/tab
432 r'(?P<value>.*)$' # everything up to eol
433 )
434
Fred Drakefce65572002-10-25 18:08:18 +0000435 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000437
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000438 The sections in setup file contains a title line at the top,
439 indicated by a name in square brackets (`[]'), plus key/value
440 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000441 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000442 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000443 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000444 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000445 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000446 optname = None
447 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000448 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000449 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 line = fp.readline()
451 if not line:
452 break
453 lineno = lineno + 1
454 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000455 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000456 continue
Fred Drake176916a2002-09-27 16:21:18 +0000457 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
458 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000459 continue
460 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000461 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000462 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000463 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000464 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000465 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000466 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000467 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000468 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000469 if mo:
470 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000471 if sectname in self._sections:
472 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000473 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000474 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000475 else:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000476 cursect = self._dict()
477 cursect['__name__'] = sectname
Fred Drakefce65572002-10-25 18:08:18 +0000478 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000479 # So sections can't start with a continuation line
480 optname = None
481 # no section header in the file?
482 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000483 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000484 # an option line?
485 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000486 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000487 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000488 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000489 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000490 # ';' is a comment delimiter only if it follows
491 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000492 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000493 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000494 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000495 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000496 # allow empty values
497 if optval == '""':
498 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000499 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000500 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000501 else:
502 # a non-fatal parsing error occurred. set up the
503 # exception but keep going. the exception will be
504 # raised at the end of the file and will contain a
505 # list of all bogus lines
506 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000507 e = ParsingError(fpname)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000508 e.append(lineno, repr(line))
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000509 # if any parsing errors occurred, raise an exception
510 if e:
511 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000512
513
514class ConfigParser(RawConfigParser):
515
Neal Norwitzf680cc42002-12-17 01:56:47 +0000516 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000517 """Get an option value for a given section.
518
519 All % interpolations are expanded in the return values, based on the
520 defaults passed into the constructor, unless the optional argument
521 `raw' is true. Additional substitutions may be provided using the
522 `vars' argument, which must be a dictionary whose contents overrides
523 any pre-existing defaults.
524
525 The section DEFAULT is special.
526 """
527 d = self._defaults.copy()
528 try:
529 d.update(self._sections[section])
530 except KeyError:
531 if section != DEFAULTSECT:
532 raise NoSectionError(section)
533 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +0000534 if vars:
535 for key, value in vars.items():
536 d[self.optionxform(key)] = value
Fred Drakefce65572002-10-25 18:08:18 +0000537 option = self.optionxform(option)
538 try:
539 value = d[option]
540 except KeyError:
541 raise NoOptionError(option, section)
542
543 if raw:
544 return value
545 else:
546 return self._interpolate(section, option, value, d)
547
Neal Norwitzf680cc42002-12-17 01:56:47 +0000548 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000549 """Return a list of tuples with (name, value) for each option
550 in the section.
551
552 All % interpolations are expanded in the return values, based on the
553 defaults passed into the constructor, unless the optional argument
554 `raw' is true. Additional substitutions may be provided using the
555 `vars' argument, which must be a dictionary whose contents overrides
556 any pre-existing defaults.
557
558 The section DEFAULT is special.
559 """
560 d = self._defaults.copy()
561 try:
562 d.update(self._sections[section])
563 except KeyError:
564 if section != DEFAULTSECT:
565 raise NoSectionError(section)
566 # Update with the entry specific variables
567 if vars:
David Goodger68a1abd2004-10-03 15:40:25 +0000568 for key, value in vars.items():
569 d[self.optionxform(key)] = value
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000570 options = list(d.keys())
Fred Drakedf393bd2002-10-25 20:41:30 +0000571 if "__name__" in options:
572 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000573 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +0000574 return [(option, d[option])
575 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000576 else:
Fred Drake8c4da532003-10-21 16:45:00 +0000577 return [(option, self._interpolate(section, option, d[option], d))
578 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000579
580 def _interpolate(self, section, option, rawval, vars):
581 # do the string interpolation
582 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000583 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000584 while depth: # Loop through this until it's done
585 depth -= 1
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000586 if "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +0000587 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +0000588 try:
589 value = value % vars
Guido van Rossumb940e112007-01-10 16:19:56 +0000590 except KeyError as e:
Fred Drakee2c64912002-12-31 17:23:27 +0000591 raise InterpolationMissingOptionError(
Brett Cannonca477b22007-03-21 22:26:20 +0000592 option, section, rawval, e.args[0])
Fred Drakefce65572002-10-25 18:08:18 +0000593 else:
594 break
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000595 if "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +0000596 raise InterpolationDepthError(option, section, rawval)
597 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000598
Fred Drakebc12b012004-05-18 02:25:51 +0000599 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
600
601 def _interpolation_replace(self, match):
602 s = match.group(1)
603 if s is None:
604 return match.group()
605 else:
606 return "%%(%s)s" % self.optionxform(s)
607
Fred Drake0eebd5c2002-10-25 21:52:00 +0000608
609class SafeConfigParser(ConfigParser):
610
611 def _interpolate(self, section, option, rawval, vars):
612 # do the string interpolation
613 L = []
614 self._interpolate_some(option, L, rawval, section, vars, 1)
615 return ''.join(L)
616
Guido van Rossumd8faa362007-04-27 19:54:29 +0000617 _interpvar_re = re.compile(r"%\(([^)]+)\)s")
618 _badpercent_re = re.compile(r"%[^%]|%$")
Fred Drake0eebd5c2002-10-25 21:52:00 +0000619
620 def _interpolate_some(self, option, accum, rest, section, map, depth):
621 if depth > MAX_INTERPOLATION_DEPTH:
622 raise InterpolationDepthError(option, section, rest)
623 while rest:
624 p = rest.find("%")
625 if p < 0:
626 accum.append(rest)
627 return
628 if p > 0:
629 accum.append(rest[:p])
630 rest = rest[p:]
631 # p is no longer used
632 c = rest[1:2]
633 if c == "%":
634 accum.append("%")
635 rest = rest[2:]
636 elif c == "(":
Guido van Rossumd8faa362007-04-27 19:54:29 +0000637 m = self._interpvar_re.match(rest)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000638 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +0000639 raise InterpolationSyntaxError(option, section,
640 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +0000641 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +0000642 rest = rest[m.end():]
643 try:
644 v = map[var]
645 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +0000646 raise InterpolationMissingOptionError(
647 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000648 if "%" in v:
649 self._interpolate_some(option, accum, v,
650 section, map, depth + 1)
651 else:
652 accum.append(v)
653 else:
654 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +0000655 option, section,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000656 "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +0000657
658 def set(self, section, option, value):
659 """Set an option. Extend ConfigParser.set: check for string values."""
Guido van Rossum3172c5d2007-10-16 18:12:55 +0000660 if not isinstance(value, str):
David Goodger1cbf2062004-10-03 15:55:09 +0000661 raise TypeError("option values must be strings")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000662 # check for bad percent signs:
663 # first, replace all "good" interpolations
664 tmp_value = self._interpvar_re.sub('', value)
665 # then, check if there's a lone percent sign left
666 m = self._badpercent_re.search(tmp_value)
667 if m:
668 raise ValueError("invalid interpolation syntax in %r at "
669 "position %d" % (value, m.start()))
David Goodger1cbf2062004-10-03 15:55:09 +0000670 ConfigParser.set(self, section, option, value)