cpython: Lib/ConfigParser.py annotate (original) (raw)
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
1 """Configuration file parser.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
3 A setup file consists of sections, lead by a "[section]" header,
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
4 and followed by "name: value" entries, with continuations and such in
5 the style of RFC 822.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
7 The option values can contain format strings which refer to other values in
8 the same section, or values in a special [DEFAULT] section.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
10 For example:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
12 something: %(dir)s/whatever
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
14 would resolve the "%(dir)s" to the value of dir. All reference
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
15 expansions are done late, on demand.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
17 Intrinsic defaults can be specified by passing them into the
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
18 ConfigParser constructor as a dictionary.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
20 class:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
22 ConfigParser -- responsible for for parsing a list of
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
23 configuration files, and managing the parsed database.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
25 methods:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
27 __init__(defaults=None)
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
28 create the parser and specify a dictionary of intrinsic defaults. The
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
29 keys must be strings, the values must be appropriate for %()s string
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
30 interpolation. Note that `__name__' is always an intrinsic default;
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
31 it's value is the section's name.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
33 sections()
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
34 return all the configuration section names, sans DEFAULT
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
41990bce023aAdded has_option(); fix bug in get() which botched interpolation if
Guido van Rossum guido@python.org
36 has_section(section)
41990bce023aAdded has_option(); fix bug in get() which botched interpolation if
Guido van Rossum guido@python.org
37 return whether the given section exists
41990bce023aAdded has_option(); fix bug in get() which botched interpolation if
Guido van Rossum guido@python.org
39 has_option(section, option)
40 return whether the given option exists in the given section
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
42 options(section)
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
43 return list of configuration options for the named section
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
45 read(filenames)
46 read and parse the list of named configuration files, given by
47 name. A single filename is also allowed. Non-existing files
48 are ignored.
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
53 messages (if fp has no `name' attribute, the string `' is used).
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
55 get(section, option, raw=0, vars=None)
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
56 return a string value for the named option. All % interpolations are
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
57 expanded in the return values, based on the defaults passed into the
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
58 constructor and the DEFAULT section. Additional substitutions may be
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
59 provided using the `vars' argument, which must be a dictionary whose
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
60 contents override any pre-existing defaults.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
62 getint(section, options)
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
63 like get(), but convert value to an integer
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
65 getfloat(section, options)
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
66 like get(), but convert value to a float
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
879e3491b661Re-format the module docstring and document the new get() argument.
Barry Warsaw barry@python.org
68 getboolean(section, options)
56f17810534cApply modified SF patch 467580: ConfigParser.getboolean(): FALSE, TRUE.
Guido van Rossum guido@python.org
69 like get(), but convert value to a boolean (currently case
56f17810534cApply modified SF patch 467580: ConfigParser.getboolean(): FALSE, TRUE.
Guido van Rossum guido@python.org
70 insensitively defined as 0, false, no, off for 0, and 1, true,
56f17810534cApply modified SF patch 467580: ConfigParser.getboolean(): FALSE, TRUE.
Guido van Rossum guido@python.org
71 yes, on for 1). Returns 0 or 1.
73 items(section, raw=0, vars=None)
74 return a list of tuples with (name, value) for each option
75 in the section.
77 remove_section(section)
78 remove the given file section and all its options
80 remove_option(section, option)
81 remove the given option from the given section
83 set(section, option, value)
84 set the given option
86 write(fp)
87 write the configuration state in .ini format
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
88 """
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
90 import re
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
92 __all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",
93 "InterpolationError","InterpolationDepthError","ParsingError",
94 "MissingSectionHeaderError","ConfigParser",
95 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
97 DEFAULTSECT = "DEFAULT"
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
99 MAX_INTERPOLATION_DEPTH = 10
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
103 # exception classes
104 class Error(Exception):
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
105 def __init__(self, msg=''):
106 self._msg = msg
107 Exception.__init__(self, msg)
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
108 def __repr__(self):
109 return self._msg
110 __str__ = __repr__
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
112 class NoSectionError(Error):
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
113 def __init__(self, section):
114 Error.__init__(self, 'No section: %s' % section)
115 self.section = section
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
117 class DuplicateSectionError(Error):
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
118 def __init__(self, section):
119 Error.__init__(self, "Section %s already exists" % section)
120 self.section = section
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
122 class NoOptionError(Error):
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
123 def __init__(self, option, section):
124 Error.__init__(self, "No option `%s' in section: %s" %
125 (option, section))
126 self.option = option
127 self.section = section
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
129 class InterpolationError(Error):
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
130 def __init__(self, reference, option, section, rawval):
131 Error.__init__(self,
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
132 "Bad value substitution:\n"
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
133 "\tsection: [%s]\n"
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
134 "\toption : %s\n"
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
135 "\tkey : %s\n"
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
136 "\trawval : %s\n"
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
137 % (section, option, reference, rawval))
138 self.reference = reference
139 self.option = option
140 self.section = section
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
142 class InterpolationDepthError(Error):
143 def __init__(self, option, section, rawval):
144 Error.__init__(self,
145 "Value interpolation too deeply recursive:\n"
146 "\tsection: [%s]\n"
147 "\toption : %s\n"
148 "\trawval : %s\n"
149 % (section, option, rawval))
150 self.option = option
151 self.section = section
153 class ParsingError(Error):
154 def __init__(self, filename):
155 Error.__init__(self, 'File contains parsing errors: %s' % filename)
156 self.filename = filename
157 self.errors = []
159 def append(self, lineno, line):
160 self.errors.append((lineno, line))
161 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
163 class MissingSectionHeaderError(ParsingError):
164 def __init__(self, filename, lineno, line):
165 Error.__init__(
166 self,
167 'File contains no section headers.\nfile: %s, line: %d\n%s' %
168 (filename, lineno, line))
169 self.filename = filename
170 self.lineno = lineno
171 self.line = line
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
175 class RawConfigParser:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
176 def __init__(self, defaults=None):
177 self._sections = {}
178 if defaults is None:
179 self._defaults = {}
180 else:
181 self._defaults = defaults
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
183 def defaults(self):
184 return self._defaults
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
186 def sections(self):
187 """Return a list of section names, excluding [DEFAULT]"""
188 # self._sections will never have [DEFAULT] in it
189 return self._sections.keys()
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
191 def add_section(self, section):
192 """Create a new section in the configuration.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
194 Raise DuplicateSectionError if a section by the specified name
195 already exists.
196 """
197 if section in self._sections:
198 raise DuplicateSectionError(section)
199 self._sections[section] = {}
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
201 def has_section(self, section):
202 """Indicate whether the named section is present in the configuration.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
204 The DEFAULT section is not acknowledged.
205 """
206 return section in self._sections
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
208 def options(self, section):
41990bce023aAdded has_option(); fix bug in get() which botched interpolation if
Guido van Rossum guido@python.org
209 """Return a list of option names for the given section name."""
210 try:
211 opts = self._sections[section].copy()
212 except KeyError:
213 raise NoSectionError(section)
214 opts.update(self._defaults)
215 if '__name__' in opts:
216 del opts['__name__']
217 return opts.keys()
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
219 def read(self, filenames):
220 """Read and parse a filename or a list of filenames.
222 Files that cannot be opened are silently ignored; this is
223 designed so that you can specify a list of potential
224 configuration file locations (e.g. current directory, user's
225 home directory, systemwide directory), and all existing
226 configuration files in the list will be read. A single
227 filename may also be given.
228 """
229 if isinstance(filenames, basestring):
230 filenames = [filenames]
231 for filename in filenames:
232 try:
233 fp = open(filename)
234 except IOError:
235 continue
236 self._read(fp, filename)
237 fp.close()
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
239 def readfp(self, fp, filename=None):
240 """Like read() but the argument must be a file-like object.
242 The `fp' argument must have a `readline' method. Optional
243 second argument is the `filename', which if not given, is
244 taken from fp.name. If fp has no `name' attribute, `' is
245 used.
247 """
248 if filename is None:
249 try:
250 filename = fp.name
251 except AttributeError:
252 filename = ''
253 self._read(fp, filename)
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
255 def get(self, section, option):
256 opt = self.optionxform(option)
257 if section not in self._sections:
258 if section != DEFAULTSECT:
259 raise NoSectionError(section)
260 if opt in self._defaults:
261 return self._defaults[opt]
262 else:
263 raise NoOptionError(option, section)
264 elif opt in self._sections[section]:
265 return self._sections[section][opt]
266 elif opt in self._defaults:
267 return self._defaults[opt]
268 else:
269 raise NoOptionError(option, section)
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
271 def items(self, section):
272 try:
273 d2 = self._sections[section]
274 except KeyError:
275 if section != DEFAULTSECT:
276 raise NoSectionError(section)
277 d2 = {}
278 d = self._defaults.copy()
279 d.update(d2)
280 if "__name__" in d:
281 del d["__name__"]
282 return d.items()
284 def _get(self, section, conv, option):
285 return conv(self.get(section, option))
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
287 def getint(self, section, option):
288 return self._get(section, int, option)
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
290 def getfloat(self, section, option):
291 return self._get(section, float, option)
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
293 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
294 '0': False, 'no': False, 'false': False, 'off': False}
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
296 def getboolean(self, section, option):
297 v = self.get(section, option)
298 if v.lower() not in self._boolean_states:
299 raise ValueError, 'Not a boolean: %s' % v
300 return self._boolean_states[v.lower()]
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of
Guido van Rossum guido@python.org
302 def optionxform(self, optionstr):
303 return optionstr.lower()
b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of
Guido van Rossum guido@python.org
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
305 def has_option(self, section, option):
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
306 """Check for the existence of a given option in a given section."""
307 if not section or section == DEFAULTSECT:
308 option = self.optionxform(option)
309 return option in self._defaults
310 elif section not in self._sections:
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
311 return 0
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
312 else:
b235160f1346Make sure ConfigParser uses .optionxform() consistently; this affects
Fred Drake fdrake@acm.org
313 option = self.optionxform(option)
314 return (option in self._sections[section]
315 or option in self._defaults)
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
317 def set(self, section, option, value):
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
318 """Set an option."""
319 if not section or section == DEFAULTSECT:
320 sectdict = self._defaults
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
321 else:
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
322 try:
323 sectdict = self._sections[section]
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
324 except KeyError:
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
325 raise NoSectionError(section)
326 sectdict[self.optionxform(option)] = value
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
328 def write(self, fp):
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
329 """Write an .ini-format representation of the configuration state."""
330 if self._defaults:
331 fp.write("[%s]\n" % DEFAULTSECT)
332 for (key, value) in self._defaults.items():
333 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
334 fp.write("\n")
335 for section in self._sections:
336 fp.write("[%s]\n" % section)
337 for (key, value) in self._sections[section].items():
338 if key != "__name__":
339 fp.write("%s = %s\n" %
340 (key, str(value).replace('\n', '\n\t')))
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
341 fp.write("\n")
4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write
Eric S. Raymond esr@thyrsus.com
3d6d218b673dSmall fixes by Petru Paler (patch #100946) checked in with esr's approval.
Thomas Wouters thomas@python.org
343 def remove_option(self, section, option):
344 """Remove an option."""
345 if not section or section == DEFAULTSECT:
346 sectdict = self._defaults
347 else:
348 try:
349 sectdict = self._sections[section]
350 except KeyError:
351 raise NoSectionError(section)
b235160f1346Make sure ConfigParser uses .optionxform() consistently; this affects
Fred Drake fdrake@acm.org
352 option = self.optionxform(option)
353 existed = option in sectdict
354 if existed:
355 del sectdict[option]
356 return existed
3d6d218b673dSmall fixes by Petru Paler (patch #100946) checked in with esr's approval.
Thomas Wouters thomas@python.org
358 def remove_section(self, section):
359 """Remove a file section."""
360 existed = section in self._sections
361 if existed:
362 del self._sections[section]
363 return existed
365 #
366 # Regular expressions for parsing section headers and options.
367 #
b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of
Guido van Rossum guido@python.org
368 SECTCRE = re.compile(
369 r'\[' # [
9ef978c6f039Be much more permissive in what we accept in section names; there has been
Fred Drake fdrake@acm.org
370 r'(?P
371 r'\]' # ]
372 )
b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of
Guido van Rossum guido@python.org
373 OPTCRE = re.compile(
374 r'(?P
375 r'\s*(?P[:=])\s*' # any number of space/tab,
376 # followed by separator
377 # (either : or =), followed
378 # by any # space/tab
379 r'(?P.*)$' # everything up to eol
380 )
382 def _read(self, fp, fpname):
383 """Parse a sectioned setup file.
5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be
Guido van Rossum guido@python.org
parents:
385 The sections in setup file contains a title line at the top,
386 indicated by a name in square brackets (`[]'), plus key/value
387 options lines, indicated by `name: value' format lines.
388 Continuation are represented by an embedded newline then
389 leading whitespace. Blank lines, lines beginning with a '#',
390 and just about everything else is ignored.
391 """
392 cursect = None # None, or a dictionary
393 optname = None
394 lineno = 0
395 e = None # None, or an exception
396 while 1:
397 line = fp.readline()
398 if not line:
399 break
400 lineno = lineno + 1
401 # comment or blank line?
402 if line.strip() == '' or line[0] in '#;':
403 continue
404 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
405 # no leading whitespace
406 continue
407 # continuation line?
408 if line[0].isspace() and cursect is not None and optname:
409 value = line.strip()
410 if value:
411 cursect[optname] = "%s\n%s" % (cursect[optname], value)
412 # a section header or option header?
413 else:
414 # is it a section header?
b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of
Guido van Rossum guido@python.org
415 mo = self.SECTCRE.match(line)
416 if mo:
417 sectname = mo.group('header')
418 if sectname in self._sections:
419 cursect = self._sections[sectname]
420 elif sectname == DEFAULTSECT:
421 cursect = self._defaults
422 else:
bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always
Barry Warsaw barry@python.org
423 cursect = {'__name__': sectname}
424 self._sections[sectname] = cursect
425 # So sections can't start with a continuation line
426 optname = None
427 # no section header in the file?
428 elif cursect is None:
429 raise MissingSectionHeaderError(fpname, lineno, `line`)
430 # an option line?
431 else:
b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of
Guido van Rossum guido@python.org
432 mo = self.OPTCRE.match(line)
433 if mo:
434 optname, vi, optval = mo.group('option', 'vi', 'value')
b975a056deb6allow comments beginning with ; in key: value as well as key = value
Jeremy Hylton jeremy@alum.mit.edu
435 if vi in ('=', ':') and ';' in optval:
436 # ';' is a comment delimiter only if it follows
437 # a spacing character
438 pos = optval.find(';')
439 if pos != -1 and optval[pos-1].isspace():
440 optval = optval[:pos]
441 optval = optval.strip()
442 # allow empty values
443 if optval == '""':
444 optval = ''
445 optname = self.optionxform(optname.rstrip())
446 cursect[optname] = optval
447 else:
448 # a non-fatal parsing error occurred. set up the
449 # exception but keep going. the exception will be
450 # raised at the end of the file and will contain a
451 # list of all bogus lines
452 if not e:
453 e = ParsingError(fpname)
454 e.append(lineno, `line`)
455 # if any parsing errors occurred, raise an exception
456 if e:
457 raise e
460 class ConfigParser(RawConfigParser):
462 def get(self, section, option, raw=0, vars=None):
463 """Get an option value for a given section.
465 All % interpolations are expanded in the return values, based on the
466 defaults passed into the constructor, unless the optional argument
467 `raw' is true. Additional substitutions may be provided using the
468 `vars' argument, which must be a dictionary whose contents overrides
469 any pre-existing defaults.
471 The section DEFAULT is special.
472 """
473 d = self._defaults.copy()
474 try:
475 d.update(self._sections[section])
476 except KeyError:
477 if section != DEFAULTSECT:
478 raise NoSectionError(section)
479 # Update with the entry specific variables
480 if vars is not None:
481 d.update(vars)
482 option = self.optionxform(option)
483 try:
484 value = d[option]
485 except KeyError:
486 raise NoOptionError(option, section)
488 if raw:
489 return value
490 else:
491 return self._interpolate(section, option, value, d)
493 def items(self, section, raw=0, vars=None):
494 """Return a list of tuples with (name, value) for each option
495 in the section.
497 All % interpolations are expanded in the return values, based on the
498 defaults passed into the constructor, unless the optional argument
499 `raw' is true. Additional substitutions may be provided using the
500 `vars' argument, which must be a dictionary whose contents overrides
501 any pre-existing defaults.
503 The section DEFAULT is special.
504 """
505 d = self._defaults.copy()
506 try:
507 d.update(self._sections[section])
508 except KeyError:
509 if section != DEFAULTSECT:
510 raise NoSectionError(section)
511 # Update with the entry specific variables
512 if vars:
513 d.update(vars)
514 options = d.keys()
515 if "__name__" in options:
516 options.remove("__name__")
517 if raw:
518 for option in options:
519 yield (option, d[option])
520 else:
521 for option in options:
522 yield (option,
523 self._interpolate(section, option, d[option], d))
525 def _interpolate(self, section, option, rawval, vars):
526 # do the string interpolation
527 value = rawval
528 depth = MAX_INTERPOLATION_DEPTH
529 while depth: # Loop through this until it's done
530 depth -= 1
531 if value.find("%(") != -1:
532 try:
533 value = value % vars
534 except KeyError, key:
535 raise InterpolationError(key, option, section, rawval)
536 else:
537 break
538 if value.find("%(") != -1:
539 raise InterpolationDepthError(option, section, rawval)
540 return value