blob: ade961479633ac9a28a353c8837f190a53f1b721 [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",
David Goodger1cbf2062004-10-03 15:55:09 +000095 "MissingSectionHeaderError",
96 "ConfigParser", "SafeConfigParser", "RawConfigParser",
Fred Drakec2ff9052002-09-27 15:33:11 +000097 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000098
Guido van Rossum3d209861997-12-09 16:10:31 +000099DEFAULTSECT = "DEFAULT"
100
Fred Drake2a37f9f2000-09-27 22:43:54 +0000101MAX_INTERPOLATION_DEPTH = 10
102
Guido van Rossum3d209861997-12-09 16:10:31 +0000103
Tim Peters88869f92001-01-14 23:36:06 +0000104
Guido van Rossum3d209861997-12-09 16:10:31 +0000105# exception classes
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000106class Error(Exception):
Fred Drake8d5dd982002-12-30 23:51:45 +0000107 """Base class for ConfigParser exceptions."""
108
Guido van Rossum3d209861997-12-09 16:10:31 +0000109 def __init__(self, msg=''):
Fred Drakee2c64912002-12-31 17:23:27 +0000110 self.message = msg
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000111 Exception.__init__(self, msg)
Fred Drake8d5dd982002-12-30 23:51:45 +0000112
Guido van Rossum3d209861997-12-09 16:10:31 +0000113 def __repr__(self):
Fred Drakee2c64912002-12-31 17:23:27 +0000114 return self.message
Fred Drake8d5dd982002-12-30 23:51:45 +0000115
Fred Drake7c1e5ad2000-12-11 18:13:19 +0000116 __str__ = __repr__
Guido van Rossum3d209861997-12-09 16:10:31 +0000117
118class NoSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000119 """Raised when no section matches a requested option."""
120
Guido van Rossum3d209861997-12-09 16:10:31 +0000121 def __init__(self, section):
Walter Dörwald70a6b492004-02-12 17:35:32 +0000122 Error.__init__(self, 'No section: %r' % (section,))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000123 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000124
125class DuplicateSectionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000126 """Raised when a section is multiply-created."""
127
Guido van Rossum3d209861997-12-09 16:10:31 +0000128 def __init__(self, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000129 Error.__init__(self, "Section %r already exists" % section)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000131
132class NoOptionError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000133 """A requested option was not found."""
134
Guido van Rossum3d209861997-12-09 16:10:31 +0000135 def __init__(self, option, section):
Fred Drakee2c64912002-12-31 17:23:27 +0000136 Error.__init__(self, "No option %r in section: %r" %
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000137 (option, section))
138 self.option = option
139 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000140
141class InterpolationError(Error):
Fred Drakee2c64912002-12-31 17:23:27 +0000142 """Base class for interpolation-related exceptions."""
Fred Drake8d5dd982002-12-30 23:51:45 +0000143
Fred Drakee2c64912002-12-31 17:23:27 +0000144 def __init__(self, option, section, msg):
145 Error.__init__(self, msg)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000146 self.option = option
147 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000148
Fred Drakee2c64912002-12-31 17:23:27 +0000149class InterpolationMissingOptionError(InterpolationError):
150 """A string substitution required a setting which was not available."""
151
152 def __init__(self, option, section, rawval, reference):
153 msg = ("Bad value substitution:\n"
154 "\tsection: [%s]\n"
155 "\toption : %s\n"
156 "\tkey : %s\n"
157 "\trawval : %s\n"
158 % (section, option, reference, rawval))
159 InterpolationError.__init__(self, option, section, msg)
160 self.reference = reference
161
162class InterpolationSyntaxError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000163 """Raised when the source text into which substitutions are made
164 does not conform to the required syntax."""
Neal Norwitzce1d9442002-12-30 23:38:47 +0000165
Fred Drakee2c64912002-12-31 17:23:27 +0000166class InterpolationDepthError(InterpolationError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000167 """Raised when substitutions are nested too deeply."""
168
Fred Drake2a37f9f2000-09-27 22:43:54 +0000169 def __init__(self, option, section, rawval):
Fred Drakee2c64912002-12-31 17:23:27 +0000170 msg = ("Value interpolation too deeply recursive:\n"
171 "\tsection: [%s]\n"
172 "\toption : %s\n"
173 "\trawval : %s\n"
174 % (section, option, rawval))
175 InterpolationError.__init__(self, option, section, msg)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000176
177class ParsingError(Error):
Fred Drake8d5dd982002-12-30 23:51:45 +0000178 """Raised when a configuration file does not follow legal syntax."""
179
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000180 def __init__(self, filename):
181 Error.__init__(self, 'File contains parsing errors: %s' % filename)
182 self.filename = filename
183 self.errors = []
184
185 def append(self, lineno, line):
186 self.errors.append((lineno, line))
Fred Drakee2c64912002-12-31 17:23:27 +0000187 self.message += '\n\t[line %2d]: %s' % (lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000188
Fred Drake2a37f9f2000-09-27 22:43:54 +0000189class MissingSectionHeaderError(ParsingError):
Fred Drake8d5dd982002-12-30 23:51:45 +0000190 """Raised when a key-value pair is found before any section header."""
191
Fred Drake2a37f9f2000-09-27 22:43:54 +0000192 def __init__(self, filename, lineno, line):
193 Error.__init__(
194 self,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000195 'File contains no section headers.\nfile: %s, line: %d\n%r' %
Fred Drake2a37f9f2000-09-27 22:43:54 +0000196 (filename, lineno, line))
197 self.filename = filename
198 self.lineno = lineno
199 self.line = line
200
Guido van Rossum3d209861997-12-09 16:10:31 +0000201
Tim Peters88869f92001-01-14 23:36:06 +0000202
Fred Drakefce65572002-10-25 18:08:18 +0000203class RawConfigParser:
Guido van Rossum3d209861997-12-09 16:10:31 +0000204 def __init__(self, defaults=None):
Fred Drakefce65572002-10-25 18:08:18 +0000205 self._sections = {}
David Goodger68a1abd2004-10-03 15:40:25 +0000206 self._defaults = {}
207 if defaults:
208 for key, value in defaults.items():
209 self._defaults[self.optionxform(key)] = value
Guido van Rossum3d209861997-12-09 16:10:31 +0000210
211 def defaults(self):
Fred Drakefce65572002-10-25 18:08:18 +0000212 return self._defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000213
214 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000215 """Return a list of section names, excluding [DEFAULT]"""
Fred Drakefce65572002-10-25 18:08:18 +0000216 # self._sections will never have [DEFAULT] in it
217 return self._sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000218
219 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000220 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000221
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000222 Raise DuplicateSectionError if a section by the specified name
223 already exists.
224 """
Fred Drakefce65572002-10-25 18:08:18 +0000225 if section in self._sections:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 raise DuplicateSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000227 self._sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000228
229 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000231
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000232 The DEFAULT section is not acknowledged.
233 """
Fred Drakefce65572002-10-25 18:08:18 +0000234 return section in self._sections
Guido van Rossum3d209861997-12-09 16:10:31 +0000235
236 def options(self, section):
Guido van Rossuma5a24b71999-10-04 19:58:22 +0000237 """Return a list of option names for the given section name."""
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000238 try:
Fred Drakefce65572002-10-25 18:08:18 +0000239 opts = self._sections[section].copy()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 except KeyError:
241 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000242 opts.update(self._defaults)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000243 if '__name__' in opts:
Fred Drake2a37f9f2000-09-27 22:43:54 +0000244 del opts['__name__']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000245 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000246
247 def read(self, filenames):
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000248 """Read and parse a filename or a list of filenames.
Tim Peters88869f92001-01-14 23:36:06 +0000249
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000250 Files that cannot be opened are silently ignored; this is
Barry Warsaw25394511999-10-12 16:12:48 +0000251 designed so that you can specify a list of potential
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000252 configuration file locations (e.g. current directory, user's
253 home directory, systemwide directory), and all existing
254 configuration files in the list will be read. A single
255 filename may also be given.
Fred Drake82903142004-05-18 04:24:02 +0000256
257 Return list of successfully read files.
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000258 """
Walter Dörwald65230a22002-06-03 15:58:32 +0000259 if isinstance(filenames, basestring):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 filenames = [filenames]
Fred Drake82903142004-05-18 04:24:02 +0000261 read_ok = []
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000262 for filename in filenames:
263 try:
264 fp = open(filename)
265 except IOError:
266 continue
Fred Drakefce65572002-10-25 18:08:18 +0000267 self._read(fp, filename)
Fred Drake2438a481999-10-04 18:11:56 +0000268 fp.close()
Fred Drake82903142004-05-18 04:24:02 +0000269 read_ok.append(filename)
270 return read_ok
Guido van Rossum3d209861997-12-09 16:10:31 +0000271
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000272 def readfp(self, fp, filename=None):
273 """Like read() but the argument must be a file-like object.
274
275 The `fp' argument must have a `readline' method. Optional
276 second argument is the `filename', which if not given, is
277 taken from fp.name. If fp has no `name' attribute, `<???>' is
278 used.
279
280 """
281 if filename is None:
282 try:
283 filename = fp.name
284 except AttributeError:
285 filename = '<???>'
Fred Drakefce65572002-10-25 18:08:18 +0000286 self._read(fp, filename)
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000287
Fred Drakefce65572002-10-25 18:08:18 +0000288 def get(self, section, option):
289 opt = self.optionxform(option)
290 if section not in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000291 if section != DEFAULTSECT:
292 raise NoSectionError(section)
Fred Drakefce65572002-10-25 18:08:18 +0000293 if opt in self._defaults:
294 return self._defaults[opt]
295 else:
296 raise NoOptionError(option, section)
297 elif opt in self._sections[section]:
298 return self._sections[section][opt]
299 elif opt in self._defaults:
300 return self._defaults[opt]
301 else:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000302 raise NoOptionError(option, section)
Fred Drake2a37f9f2000-09-27 22:43:54 +0000303
Fred Drakefce65572002-10-25 18:08:18 +0000304 def items(self, section):
Fred Drake2ca041f2002-09-27 15:49:56 +0000305 try:
Fred Drakefce65572002-10-25 18:08:18 +0000306 d2 = self._sections[section]
Fred Drake2ca041f2002-09-27 15:49:56 +0000307 except KeyError:
308 if section != DEFAULTSECT:
309 raise NoSectionError(section)
Fred Drakedf393bd2002-10-25 20:41:30 +0000310 d2 = {}
Fred Drakefce65572002-10-25 18:08:18 +0000311 d = self._defaults.copy()
312 d.update(d2)
Fred Drakedf393bd2002-10-25 20:41:30 +0000313 if "__name__" in d:
314 del d["__name__"]
Fred Drakefce65572002-10-25 18:08:18 +0000315 return d.items()
Fred Drake2ca041f2002-09-27 15:49:56 +0000316
Fred Drakefce65572002-10-25 18:08:18 +0000317 def _get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000318 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000319
320 def getint(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000321 return self._get(section, int, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000322
323 def getfloat(self, section, option):
Fred Drakefce65572002-10-25 18:08:18 +0000324 return self._get(section, float, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000325
Fred Drakec2ff9052002-09-27 15:33:11 +0000326 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
327 '0': False, 'no': False, 'false': False, 'off': False}
328
Guido van Rossum3d209861997-12-09 16:10:31 +0000329 def getboolean(self, section, option):
Tim Peterse0c446b2001-10-18 21:57:37 +0000330 v = self.get(section, option)
Fred Drakec2ff9052002-09-27 15:33:11 +0000331 if v.lower() not in self._boolean_states:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000332 raise ValueError, 'Not a boolean: %s' % v
Fred Drakec2ff9052002-09-27 15:33:11 +0000333 return self._boolean_states[v.lower()]
Guido van Rossum3d209861997-12-09 16:10:31 +0000334
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000335 def optionxform(self, optionstr):
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000336 return optionstr.lower()
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000337
Eric S. Raymond417c4892000-07-10 18:11:00 +0000338 def has_option(self, section, option):
339 """Check for the existence of a given option in a given section."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000340 if not section or section == DEFAULTSECT:
341 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000342 return option in self._defaults
343 elif section not in self._sections:
Neal Norwitzf680cc42002-12-17 01:56:47 +0000344 return False
Eric S. Raymond417c4892000-07-10 18:11:00 +0000345 else:
Fred Drake3c823aa2001-02-26 21:55:34 +0000346 option = self.optionxform(option)
Fred Drakefce65572002-10-25 18:08:18 +0000347 return (option in self._sections[section]
348 or option in self._defaults)
Eric S. Raymond417c4892000-07-10 18:11:00 +0000349
350 def set(self, section, option, value):
351 """Set an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000352 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000353 sectdict = self._defaults
Eric S. Raymond417c4892000-07-10 18:11:00 +0000354 else:
355 try:
Fred Drakefce65572002-10-25 18:08:18 +0000356 sectdict = self._sections[section]
Eric S. Raymond417c4892000-07-10 18:11:00 +0000357 except KeyError:
358 raise NoSectionError(section)
Fred Drakec2ff9052002-09-27 15:33:11 +0000359 sectdict[self.optionxform(option)] = value
Eric S. Raymond417c4892000-07-10 18:11:00 +0000360
361 def write(self, fp):
362 """Write an .ini-format representation of the configuration state."""
Fred Drakefce65572002-10-25 18:08:18 +0000363 if self._defaults:
Fred Drakec2ff9052002-09-27 15:33:11 +0000364 fp.write("[%s]\n" % DEFAULTSECT)
Fred Drakefce65572002-10-25 18:08:18 +0000365 for (key, value) in self._defaults.items():
Andrew M. Kuchling00824ed2002-03-08 18:08:47 +0000366 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000367 fp.write("\n")
Fred Drakefce65572002-10-25 18:08:18 +0000368 for section in self._sections:
Fred Drakec2ff9052002-09-27 15:33:11 +0000369 fp.write("[%s]\n" % section)
Fred Drakefce65572002-10-25 18:08:18 +0000370 for (key, value) in self._sections[section].items():
Fred Drakec2ff9052002-09-27 15:33:11 +0000371 if key != "__name__":
372 fp.write("%s = %s\n" %
373 (key, str(value).replace('\n', '\n\t')))
Eric S. Raymond417c4892000-07-10 18:11:00 +0000374 fp.write("\n")
375
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000376 def remove_option(self, section, option):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000377 """Remove an option."""
Fred Drakec2ff9052002-09-27 15:33:11 +0000378 if not section or section == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000379 sectdict = self._defaults
Eric S. Raymond649685a2000-07-14 14:28:22 +0000380 else:
381 try:
Fred Drakefce65572002-10-25 18:08:18 +0000382 sectdict = self._sections[section]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000383 except KeyError:
384 raise NoSectionError(section)
Fred Drake3c823aa2001-02-26 21:55:34 +0000385 option = self.optionxform(option)
Raymond Hettinger54f02222002-06-01 14:18:47 +0000386 existed = option in sectdict
Eric S. Raymond649685a2000-07-14 14:28:22 +0000387 if existed:
Fred Drakeff4a23b2000-12-04 16:29:13 +0000388 del sectdict[option]
Eric S. Raymond649685a2000-07-14 14:28:22 +0000389 return existed
390
Thomas Woutersff4df6d2000-07-21 05:19:59 +0000391 def remove_section(self, section):
Eric S. Raymond649685a2000-07-14 14:28:22 +0000392 """Remove a file section."""
Fred Drakefce65572002-10-25 18:08:18 +0000393 existed = section in self._sections
Fred Drakec2ff9052002-09-27 15:33:11 +0000394 if existed:
Fred Drakefce65572002-10-25 18:08:18 +0000395 del self._sections[section]
Fred Drakec2ff9052002-09-27 15:33:11 +0000396 return existed
Eric S. Raymond649685a2000-07-14 14:28:22 +0000397
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000398 #
Fred Drakec2ff9052002-09-27 15:33:11 +0000399 # Regular expressions for parsing section headers and options.
400 #
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000401 SECTCRE = re.compile(
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000402 r'\[' # [
Fred Draked4df94b2001-02-14 15:24:17 +0000403 r'(?P<header>[^]]+)' # very permissive!
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000404 r'\]' # ]
405 )
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000406 OPTCRE = re.compile(
Fred Drake176916a2002-09-27 16:21:18 +0000407 r'(?P<option>[^:=\s][^:=]*)' # very permissive!
Fred Drakec2ff9052002-09-27 15:33:11 +0000408 r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000409 # followed by separator
410 # (either : or =), followed
411 # by any # space/tab
412 r'(?P<value>.*)$' # everything up to eol
413 )
414
Fred Drakefce65572002-10-25 18:08:18 +0000415 def _read(self, fp, fpname):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000416 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000417
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000418 The sections in setup file contains a title line at the top,
419 indicated by a name in square brackets (`[]'), plus key/value
420 options lines, indicated by `name: value' format lines.
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000421 Continuations are represented by an embedded newline then
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 leading whitespace. Blank lines, lines beginning with a '#',
Andrew M. Kuchling9050a512002-11-06 14:51:20 +0000423 and just about everything else are ignored.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000424 """
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000425 cursect = None # None, or a dictionary
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 optname = None
427 lineno = 0
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000428 e = None # None, or an exception
Neal Norwitzf680cc42002-12-17 01:56:47 +0000429 while True:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000430 line = fp.readline()
431 if not line:
432 break
433 lineno = lineno + 1
434 # comment or blank line?
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000435 if line.strip() == '' or line[0] in '#;':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 continue
Fred Drake176916a2002-09-27 16:21:18 +0000437 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
438 # no leading whitespace
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000439 continue
440 # continuation line?
Fred Drakec2ff9052002-09-27 15:33:11 +0000441 if line[0].isspace() and cursect is not None and optname:
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000442 value = line.strip()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000443 if value:
Fred Drakec2ff9052002-09-27 15:33:11 +0000444 cursect[optname] = "%s\n%s" % (cursect[optname], value)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000445 # a section header or option header?
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000446 else:
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000447 # is it a section header?
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000448 mo = self.SECTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000449 if mo:
450 sectname = mo.group('header')
Fred Drakefce65572002-10-25 18:08:18 +0000451 if sectname in self._sections:
452 cursect = self._sections[sectname]
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000453 elif sectname == DEFAULTSECT:
Fred Drakefce65572002-10-25 18:08:18 +0000454 cursect = self._defaults
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000455 else:
Barry Warsaw64462121998-08-06 18:48:41 +0000456 cursect = {'__name__': sectname}
Fred Drakefce65572002-10-25 18:08:18 +0000457 self._sections[sectname] = cursect
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000458 # So sections can't start with a continuation line
459 optname = None
460 # no section header in the file?
461 elif cursect is None:
Walter Dörwald70a6b492004-02-12 17:35:32 +0000462 raise MissingSectionHeaderError(fpname, lineno, line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000463 # an option line?
464 else:
Guido van Rossum9e480ad1999-06-17 18:41:42 +0000465 mo = self.OPTCRE.match(line)
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000466 if mo:
Fred Drakec517b9b2000-02-28 20:59:03 +0000467 optname, vi, optval = mo.group('option', 'vi', 'value')
Jeremy Hylton820314e2000-03-03 20:43:57 +0000468 if vi in ('=', ':') and ';' in optval:
Fred Drakec517b9b2000-02-28 20:59:03 +0000469 # ';' is a comment delimiter only if it follows
470 # a spacing character
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000471 pos = optval.find(';')
Fred Drakec2ff9052002-09-27 15:33:11 +0000472 if pos != -1 and optval[pos-1].isspace():
Fred Drakec517b9b2000-02-28 20:59:03 +0000473 optval = optval[:pos]
Eric S. Raymond9eb54d92001-02-09 05:19:09 +0000474 optval = optval.strip()
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000475 # allow empty values
476 if optval == '""':
477 optval = ''
Fred Drake176916a2002-09-27 16:21:18 +0000478 optname = self.optionxform(optname.rstrip())
Fred Drakec2ff9052002-09-27 15:33:11 +0000479 cursect[optname] = optval
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000480 else:
481 # a non-fatal parsing error occurred. set up the
482 # exception but keep going. the exception will be
483 # raised at the end of the file and will contain a
484 # list of all bogus lines
485 if not e:
Guido van Rossum6a8d84b1999-10-04 18:57:27 +0000486 e = ParsingError(fpname)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000487 e.append(lineno, repr(line))
Barry Warsawbfa3f6b1998-07-01 20:41:12 +0000488 # if any parsing errors occurred, raise an exception
489 if e:
490 raise e
Fred Drakefce65572002-10-25 18:08:18 +0000491
492
493class ConfigParser(RawConfigParser):
494
Neal Norwitzf680cc42002-12-17 01:56:47 +0000495 def get(self, section, option, raw=False, vars=None):
Fred Drakefce65572002-10-25 18:08:18 +0000496 """Get an option value for a given section.
497
498 All % interpolations are expanded in the return values, based on the
499 defaults passed into the constructor, unless the optional argument
500 `raw' is true. Additional substitutions may be provided using the
501 `vars' argument, which must be a dictionary whose contents overrides
502 any pre-existing defaults.
503
504 The section DEFAULT is special.
505 """
506 d = self._defaults.copy()
507 try:
508 d.update(self._sections[section])
509 except KeyError:
510 if section != DEFAULTSECT:
511 raise NoSectionError(section)
512 # Update with the entry specific variables
David Goodger68a1abd2004-10-03 15:40:25 +0000513 if vars:
514 for key, value in vars.items():
515 d[self.optionxform(key)] = value
Fred Drakefce65572002-10-25 18:08:18 +0000516 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:
David Goodger68a1abd2004-10-03 15:40:25 +0000547 for key, value in vars.items():
548 d[self.optionxform(key)] = value
Fred Drakedf393bd2002-10-25 20:41:30 +0000549 options = d.keys()
550 if "__name__" in options:
551 options.remove("__name__")
Fred Drakefce65572002-10-25 18:08:18 +0000552 if raw:
Fred Drake8c4da532003-10-21 16:45:00 +0000553 return [(option, d[option])
554 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000555 else:
Fred Drake8c4da532003-10-21 16:45:00 +0000556 return [(option, self._interpolate(section, option, d[option], d))
557 for option in options]
Fred Drakefce65572002-10-25 18:08:18 +0000558
559 def _interpolate(self, section, option, rawval, vars):
560 # do the string interpolation
561 value = rawval
Tim Peters230a60c2002-11-09 05:08:07 +0000562 depth = MAX_INTERPOLATION_DEPTH
Fred Drakefce65572002-10-25 18:08:18 +0000563 while depth: # Loop through this until it's done
564 depth -= 1
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000565 if "%(" in value:
Fred Drakebc12b012004-05-18 02:25:51 +0000566 value = self._KEYCRE.sub(self._interpolation_replace, value)
Fred Drakefce65572002-10-25 18:08:18 +0000567 try:
568 value = value % vars
Fred Drake00dc5a92002-12-31 06:55:41 +0000569 except KeyError, e:
Fred Drakee2c64912002-12-31 17:23:27 +0000570 raise InterpolationMissingOptionError(
571 option, section, rawval, e[0])
Fred Drakefce65572002-10-25 18:08:18 +0000572 else:
573 break
Raymond Hettingerbac788a2004-05-04 09:21:43 +0000574 if "%(" in value:
Fred Drakefce65572002-10-25 18:08:18 +0000575 raise InterpolationDepthError(option, section, rawval)
576 return value
Fred Drake0eebd5c2002-10-25 21:52:00 +0000577
Fred Drakebc12b012004-05-18 02:25:51 +0000578 _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
579
580 def _interpolation_replace(self, match):
581 s = match.group(1)
582 if s is None:
583 return match.group()
584 else:
585 return "%%(%s)s" % self.optionxform(s)
586
Fred Drake0eebd5c2002-10-25 21:52:00 +0000587
588class SafeConfigParser(ConfigParser):
589
590 def _interpolate(self, section, option, rawval, vars):
591 # do the string interpolation
592 L = []
593 self._interpolate_some(option, L, rawval, section, vars, 1)
594 return ''.join(L)
595
596 _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
597
598 def _interpolate_some(self, option, accum, rest, section, map, depth):
599 if depth > MAX_INTERPOLATION_DEPTH:
600 raise InterpolationDepthError(option, section, rest)
601 while rest:
602 p = rest.find("%")
603 if p < 0:
604 accum.append(rest)
605 return
606 if p > 0:
607 accum.append(rest[:p])
608 rest = rest[p:]
609 # p is no longer used
610 c = rest[1:2]
611 if c == "%":
612 accum.append("%")
613 rest = rest[2:]
614 elif c == "(":
615 m = self._interpvar_match(rest)
616 if m is None:
Neal Norwitz10f30182003-06-29 04:23:35 +0000617 raise InterpolationSyntaxError(option, section,
618 "bad interpolation variable reference %r" % rest)
Fred Drakebc12b012004-05-18 02:25:51 +0000619 var = self.optionxform(m.group(1))
Fred Drake0eebd5c2002-10-25 21:52:00 +0000620 rest = rest[m.end():]
621 try:
622 v = map[var]
623 except KeyError:
Fred Drakee2c64912002-12-31 17:23:27 +0000624 raise InterpolationMissingOptionError(
625 option, section, rest, var)
Fred Drake0eebd5c2002-10-25 21:52:00 +0000626 if "%" in v:
627 self._interpolate_some(option, accum, v,
628 section, map, depth + 1)
629 else:
630 accum.append(v)
631 else:
632 raise InterpolationSyntaxError(
Neal Norwitz10f30182003-06-29 04:23:35 +0000633 option, section,
Walter Dörwald70a6b492004-02-12 17:35:32 +0000634 "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
David Goodger1cbf2062004-10-03 15:55:09 +0000635
636 def set(self, section, option, value):
637 """Set an option. Extend ConfigParser.set: check for string values."""
638 if not isinstance(value, basestring):
639 raise TypeError("option values must be strings")
640 ConfigParser.set(self, section, option, value)