blob: 5f80269407c0dfc605875f7032159f98327457ac [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;
31 it's 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
Guido van Rossum3d209861997-12-09 16:10:31 +000091
Fred Drake8d5dd982002-12-30 23:51:45 +000092__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
93 "InterpolationError", "InterpolationDepthError",
94 "InterpolationSyntaxError", "ParsingError",
Raymond Hettinger99c2d532003-09-01 23:30:44 +000095 "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000096 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000097
Guido van Rossum3d209861997-12-09 16:10:31 +000098DEFAULTSECT = "DEFAULT"
99
Fred Drake2a37f9f2000-09-27 22:43:54 +0000100MAX_INTERPOLATION_DEPTH = 10
101
Guido van Rossum3d209861997-12-09 16:10:31 +0000102
Tim Peters88869f92001-01-14 23:36:06 +0000103
Guido van Rossum3d209861997-12-09 16:10:31 +0000104# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000105class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000106 """Base class for ConfigParser exceptions."""
107
Guido van Rossum3d209861997-12-09 16:10:31 +0000108 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000109 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000110 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000111
Guido van Rossum3d209861997-12-09 16:10:31 +0000112 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000113 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000114
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000115 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000116
117class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000118 """Raised when no section matches a requested option."""
119
Guido van Rossum3d209861997-12-09 16:10:31 +0000120 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000121 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000122 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000123
124class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000125 """Raised when a section is multiply-created."""
126
Guido van Rossum3d209861997-12-09 16:10:31 +0000127 def __init__(self, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000128 Error.__init__(self, "Section %r already exists" % section)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000129 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000130
131class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000132 """A requested option was not found."""
133
Guido van Rossum3d209861997-12-09 16:10:31 +0000134 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000135 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000136 (option, section))
137 self.option = option
138 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000139
140class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000141 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000142
Fred Drakee2c64912002-12-31 17:23:27 +0000143 def __init__(self, option, section, msg):
144 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 self.option = option
146 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000147
Fred Drakee2c64912002-12-31 17:23:27 +0000148class InterpolationMissingOptionError(InterpolationError):
149 """A string substitution required a setting which was not available."""
150
151 def __init__(self, option, section, rawval, reference):
152 msg = ("Bad value substitution:\n"
153 "\tsection: [%s]\n"
154 "\toption : %s\n"
155 "\tkey : %s\n"
156 "\trawval : %s\n"
157 % (section, option, reference, rawval))
158 InterpolationError.__init__(self, option, section, msg)
159 self.reference = reference
160
161class InterpolationSyntaxError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000162 """Raised when the source text into which substitutions are made
163 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000164
Fred Drakee2c64912002-12-31 17:23:27 +0000165class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000166 """Raised when substitutions are nested too deeply."""
167
Fred Drake2a37f9f2000-09-27 22:43:54 +0000168 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000169 msg = ("Value interpolation too deeply recursive:\n"
170 "\tsection: [%s]\n"
171 "\toption : %s\n"
172 "\trawval : %s\n"
173 % (section, option, rawval))
174 InterpolationError.__init__(self, option, section, msg)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000175
176class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000177 """Raised when a configuration file does not follow legal syntax."""
178
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000179 def __init__(self, filename):
180 Error.__init__(self, 'File contains parsing errors: %s' % filename)
181 self.filename = filename
182 self.errors = []
183
184 def append(self, lineno, line):
185 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000186 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000187
Fred Drake2a37f9f2000-09-27 22:43:54 +0000188class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000189 """Raised when a key-value pair is found before any section header."""
190
Fred Drake2a37f9f2000-09-27 22:43:54 +0000191 def __init__(self, filename, lineno, line):
192 Error.__init__(
193 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000194 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000195 (filename, lineno, line))
196 self.filename = filename
197 self.lineno = lineno
198 self.line = line
199
Guido van Rossum3d209861997-12-09 16:10:31 +0000200
Tim Peters88869f92001-01-14 23:36:06 +0000201
Fred Drakefce65572002-10-25 18:08:18 +0000202class RawConfigParser:
Guido van Rossum3d209861997-12-09 16:10:31 +0000203 def __init__(self, defaults=None):
Fred Drakefce65572002-10-25 18:08:18 +0000204 self._sections = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 if defaults is None:
Fred Drakefce65572002-10-25 18:08:18 +0000206 self._defaults = {}
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000207 else:
Fred Drakefce65572002-10-25 18:08:18 +0000208 self._defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000209
210 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000211 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000212
213 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000214 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000215 # self._sections will never have [DEFAULT] in it
216 return self._sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000217
218 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000219 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000220
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 Raise DuplicateSectionError if a section by the specified name
222 already exists.
223 """
Fred Drakefce65572002-10-25 18:08:18 +0000224 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000225 raise DuplicateSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000226 self._sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000227
228 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000229 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000230
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000231 The DEFAULT section is not acknowledged.
232 """
Fred Drakefce65572002-10-25 18:08:18 +0000233 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000234
235 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000236 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 try:
Fred Drakefce65572002-10-25 18:08:18 +0000238 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000239 except KeyError:
240 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000241 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000242 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000243 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000244 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000245
246 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000247 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000248
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000249 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000250 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000251 configuration file locations (e.g. current directory, user's
252 home directory, systemwide directory), and all existing
253 configuration files in the list will be read. A single
254 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000255
256 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000257 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000258 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000259 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000260 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000261 for filename in filenames:
262 try:
263 fp = open(filename)
264 except IOError:
265 continue
Fred Drakefce65572002-10-25 18:08:18 +0000266 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000267 fp.close()
Fred Drake82903142004-05-18 04:24:02 +0000268 read_ok.append(filename)
269 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000270
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000271 def readfp(self, fp, filename=None):
272 """Like read() but the argument must be a file-like object.
273
274 The `fp' argument must have a `readline' method. Optional
275 second argument is the `filename', which if not given, is
276 taken from fp.name. If fp has no `name' attribute, `<???>' is
277 used.
278
279 """
280 if filename is None:
281 try:
282 filename = fp.name
283 except AttributeError:
284 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000285 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000286
Fred Drakefce65572002-10-25 18:08:18 +0000287 def get(self, section, option):
288 opt = self.optionxform(option)
289 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000290 if section != DEFAULTSECT:
291 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000292 if opt in self._defaults:
293 return self._defaults[opt]
294 else:
295 raise NoOptionError(option, section)
296 elif opt in self._sections[section]:
297 return self._sections[section][opt]
298 elif opt in self._defaults:
299 return self._defaults[opt]
300 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000301 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000302
Fred Drakefce65572002-10-25 18:08:18 +0000303 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000304 try:
Fred Drakefce65572002-10-25 18:08:18 +0000305 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000306 except KeyError:
307 if section != DEFAULTSECT:
308 raise NoSectionError(section)
Fred Drakedf393bd2002-10-25 20:41:30 +0000309 d2 = {}
Fred Drakefce65572002-10-25 18:08:18 +0000310 d = self._defaults.copy()
311 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000312 if "__name__" in d:
313 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000314 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000315
Fred Drakefce65572002-10-25 18:08:18 +0000316 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000317 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000318
319 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000320 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000321
322 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000323 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000324
Fred Drakec2ff9052002-09-27 15:33:11 +0000325 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
326 '0': False, 'no': False, 'false': False, 'off': False}
327
Guido van Rossum3d209861997-12-09 16:10:31 +0000328 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000329 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000330 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000331 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000332 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000333
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000334 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000335 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000336
Eric S. Raymond417c4892000-07-10 18:11:00 +0000337 def has_option(self, section, option):
338 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000339 if not section or section == DEFAULTSECT:
340 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000341 return option in self._defaults
342 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000343 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000344 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000345 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000346 return (option in self._sections[section]
347 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000348
349 def set(self, section, option, value):
350 """Set an option."""
Fred Drakeabc086f2004-05-18 03:29:52 +0000351 if not isinstance(value, basestring):
352 raise TypeError("option values must be strings")
Fred Drakec2ff9052002-09-27 15:33:11 +0000353 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000354 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000355 else:
356 try:
Fred Drakefce65572002-10-25 18:08:18 +0000357 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000358 except KeyError:
359 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000360 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000361
362 def write(self, fp):
363 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000364 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000365 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000366 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000367 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000368 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000369 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000370 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000371 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000372 if key != "__name__":
373 fp.write("%s = %s\n" %
374 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000375 fp.write("\n")
376
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000377 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000378 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000379 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000380 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000381 else:
382 try:
Fred Drakefce65572002-10-25 18:08:18 +0000383 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000384 except KeyError:
385 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000386 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000387 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000388 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000389 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000390 return existed
391
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000392 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000393 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000394 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000395 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000396 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000397 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000398
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000399 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000400 # Regular expressions for parsing section headers and options.
401 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000402 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000403 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000404 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000405 r'\]' # ]
406 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000407 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000408 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000409 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000410 # followed by separator
411 # (either : or =), followed
412 # by any # space/tab
413 r'(?P<value>.*)$' # everything up to eol
414 )
415
Fred Drakefce65572002-10-25 18:08:18 +0000416 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000417 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000418
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000419 The sections in setup file contains a title line at the top,
420 indicated by a name in square brackets (`[]'), plus key/value
421 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000422 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000424 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000425 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000426 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000427 optname = None
428 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000429 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000430 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000431 line = fp.readline()
432 if not line:
433 break
434 lineno = lineno + 1
435 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000436 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000437 continue
Fred Drake176916a2002-09-27 16:21:18 +0000438 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
439 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000440 continue
441 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000442 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000443 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000444 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000445 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000446 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000447 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000448 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000449 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000450 if mo:
451 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000452 if sectname in self._sections:
453 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000454 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000455 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000456 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000457 cursect = {'__name__': sectname}
Fred Drakefce65572002-10-25 18:08:18 +0000458 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000459 # So sections can't start with a continuation line
460 optname = None
461 # no section header in the file?
462 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000463 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000464 # an option line?
465 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000466 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000467 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000468 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000469 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000470 # ';' is a comment delimiter only if it follows
471 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000472 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000473 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000474 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000475 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000476 # allow empty values
477 if optval == '""':
478 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000479 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000480 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000481 else:
482 # a non-fatal parsing error occurred. set up the
483 # exception but keep going. the exception will be
484 # raised at the end of the file and will contain a
485 # list of all bogus lines
486 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000487 e = ParsingError(fpname)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000488 e.append(lineno, repr(line))
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000489 # if any parsing errors occurred, raise an exception
490 if e:
491 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000492
493
494class ConfigParser(RawConfigParser):
495
Neal Norwitzf680cc42002-12-17 01:56:47 +0000496 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000497 """Get an option value for a given section.
498
499 All % interpolations are expanded in the return values, based on the
500 defaults passed into the constructor, unless the optional argument
501 `raw' is true. Additional substitutions may be provided using the
502 `vars' argument, which must be a dictionary whose contents overrides
503 any pre-existing defaults.
504
505 The section DEFAULT is special.
506 """
507 d = self._defaults.copy()
508 try:
509 d.update(self._sections[section])
510 except KeyError:
511 if section != DEFAULTSECT:
512 raise NoSectionError(section)
513 # Update with the entry specific variables
514 if vars is not None:
515 d.update(vars)
516 option = self.optionxform(option)
517 try:
518 value = d[option]
519 except KeyError:
520 raise NoOptionError(option, section)
521
522 if raw:
523 return value
524 else:
525 return self._interpolate(section, option, value, d)
526
Neal Norwitzf680cc42002-12-17 01:56:47 +0000527 def items(self, section, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000528 """Return a list of tuples with (name, value) for each option
529 in the section.
530
531 All % interpolations are expanded in the return values, based on the
532 defaults passed into the constructor, unless the optional argument
533 `raw' is true. Additional substitutions may be provided using the
534 `vars' argument, which must be a dictionary whose contents overrides
535 any pre-existing defaults.
536
537 The section DEFAULT is special.
538 """
539 d = self._defaults.copy()
540 try:
541 d.update(self._sections[section])
542 except KeyError:
543 if section != DEFAULTSECT:
544 raise NoSectionError(section)
545 # Update with the entry specific variables
546 if vars:
547 d.update(vars)
Fred Drakedf393bd2002-10-25 20:41:30 +0000548 options = d.keys()
549 if "__name__" in options:
550 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000551 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +0000552 return [(option, d[option])
553 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000554 else:
Fred Drake8c4da532003-10-21 16:45:00 +0000555 return [(option, self._interpolate(section, option, d[option], d))
556 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000557
558 def _interpolate(self, section, option, rawval, vars):
559 # do the string interpolation
560 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000561 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000562 while depth: # Loop through this until it's done
563 depth -= 1
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000564 if "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +0000565 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +0000566 try:
567 value = value % vars
Fred Drake00dc5a92002-12-31 06:55:41 +0000568 except KeyError, e:
Fred Drakee2c64912002-12-31 17:23:27 +0000569 raise InterpolationMissingOptionError(
570 option, section, rawval, e[0])
Fred Drakefce65572002-10-25 18:08:18 +0000571 else:
572 break
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000573 if "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +0000574 raise InterpolationDepthError(option, section, rawval)
575 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000576
Fred Drakebc12b012004-05-18 02:25:51 +0000577 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
578
579 def _interpolation_replace(self, match):
580 s = match.group(1)
581 if s is None:
582 return match.group()
583 else:
584 return "%%(%s)s" % self.optionxform(s)
585
Fred Drake0eebd5c2002-10-25 21:52:00 +0000586
587class SafeConfigParser(ConfigParser):
588
589 def _interpolate(self, section, option, rawval, vars):
590 # do the string interpolation
591 L = []
592 self._interpolate_some(option, L, rawval, section, vars, 1)
593 return ''.join(L)
594
595 _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
596
597 def _interpolate_some(self, option, accum, rest, section, map, depth):
598 if depth > MAX_INTERPOLATION_DEPTH:
599 raise InterpolationDepthError(option, section, rest)
600 while rest:
601 p = rest.find("%")
602 if p < 0:
603 accum.append(rest)
604 return
605 if p > 0:
606 accum.append(rest[:p])
607 rest = rest[p:]
608 # p is no longer used
609 c = rest[1:2]
610 if c == "%":
611 accum.append("%")
612 rest = rest[2:]
613 elif c == "(":
614 m = self._interpvar_match(rest)
615 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +0000616 raise InterpolationSyntaxError(option, section,
617 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +0000618 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +0000619 rest = rest[m.end():]
620 try:
621 v = map[var]
622 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +0000623 raise InterpolationMissingOptionError(
624 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000625 if "%" in v:
626 self._interpolate_some(option, accum, v,
627 section, map, depth + 1)
628 else:
629 accum.append(v)
630 else:
631 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +0000632 option, section,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000633 "'%%' must be followed by '%%' or '(', found: %r" % (rest,))