blob: 957222c27f77657dcd38ffb10cdc182e0f08c34b [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
5the style of rfc822.
6
7The option values can contain format strings which refer to other
8values in the same section, or values in a special [DEFAULT] section.
9For example:
10
11 something: %(dir)s/whatever
12
13would resolve the "%(dir)s" to the value of dir. All reference
14expansions are done late, on demand.
15
16Intrinsic defaults can be specified by passing them into the
17ConfigParser constructor as a dictionary.
18
19class:
20
21ConfigParser -- responsible for for parsing a list of
22 configuration files, and managing the parsed database.
23
24 methods:
25
26 __init__(defaults=None) -- create the parser and specify a
27 dictionary of intrinsic defaults. The
28 keys must be strings, the values must
29 be appropriate for %()s string
30 interpolation. Note that `name' is
31 always an intrinsic default; it's value
32 is the section's name.
33
34 sections() -- return all the configuration section names, sans DEFAULT
35
36 options(section) -- return list of configuration options for the named
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000037 section
Guido van Rossum3d209861997-12-09 16:10:31 +000038
39 read(*filenames) -- read and parse the list of named configuration files
40
41 get(section, option, raw=0) -- return a string value for the named
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000042 option. All % interpolations are
43 expanded in the return values, based on
44 the defaults passed into the constructor
45 and the DEFAULT section.
Guido van Rossum3d209861997-12-09 16:10:31 +000046
47 getint(section, options) -- like get(), but convert value to an integer
48
49 getfloat(section, options) -- like get(), but convert value to a float
50
51 getboolean(section, options) -- like get(), but convert value to
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000052 a boolean (currently defined as 0
53 or 1, only)
Guido van Rossum3d209861997-12-09 16:10:31 +000054"""
55
56import sys
57import string
58import regex
59from types import ListType
60
61
62SECTHEAD_RE = "^\[\([-A-Za-z0-9]*\)\][" + string.whitespace + "]*$"
63secthead_cre = regex.compile(SECTHEAD_RE)
64OPTION_RE = "^\([-A-Za-z0-9.]+\)\(:\|[" + string.whitespace + "]*=\)\(.*\)$"
65option_cre = regex.compile(OPTION_RE)
66
67DEFAULTSECT = "DEFAULT"
68
69
70
71# exception classes
72class Error:
73 def __init__(self, msg=''):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000074 self.__msg = msg
Guido van Rossum3d209861997-12-09 16:10:31 +000075 def __repr__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000076 return self.__msg
Guido van Rossum3d209861997-12-09 16:10:31 +000077
78class NoSectionError(Error):
79 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000080 Error.__init__(self, 'No section: %s' % section)
81 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000082
83class DuplicateSectionError(Error):
84 def __init__(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000085 Error.__init__(self, "Section %s already exists" % section)
86 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000087
88class NoOptionError(Error):
89 def __init__(self, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000090 Error.__init__(self, "No option `%s' in section: %s" %
91 (option, section))
92 self.option = option
93 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +000094
95class InterpolationError(Error):
96 def __init__(self, reference, option, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000097 Error.__init__(self,
98 "Bad value substitution: sect `%s', opt `%s', ref `%s'"
99 % (section, option, reference))
100 self.reference = reference
101 self.option = option
102 self.section = section
Guido van Rossum3d209861997-12-09 16:10:31 +0000103
104
105
106class ConfigParser:
107 def __init__(self, defaults=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000108 self.__sections = {}
109 if defaults is None:
110 self.__defaults = {}
111 else:
112 self.__defaults = defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000113
114 def defaults(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000115 return self.__defaults
Guido van Rossum3d209861997-12-09 16:10:31 +0000116
117 def sections(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000118 """Return a list of section names, excluding [DEFAULT]"""
119 # self.__sections will never have [DEFAULT] in it
120 return self.__sections.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000121
122 def add_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000123 """Create a new section in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000124
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000125 Raise DuplicateSectionError if a section by the specified name
126 already exists.
127 """
128 if self.__sections.has_key(section):
129 raise DuplicateSectionError(section)
130 self.__sections[section] = {}
Guido van Rossum3d209861997-12-09 16:10:31 +0000131
132 def has_section(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000133 """Indicate whether the named section is present in the configuration.
Guido van Rossum3d209861997-12-09 16:10:31 +0000134
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 The DEFAULT section is not acknowledged.
136 """
137 return self.__sections.has_key(section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000138
139 def options(self, section):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000140 try:
141 opts = self.__sections[section].copy()
142 except KeyError:
143 raise NoSectionError(section)
144 opts.update(self.__defaults)
145 return opts.keys()
Guido van Rossum3d209861997-12-09 16:10:31 +0000146
147 def read(self, filenames):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000148 """Read and parse a list of filenames."""
149 if type(filenames) is type(''):
150 filenames = [filenames]
151 for file in filenames:
152 try:
153 fp = open(file, 'r')
154 self.__read(fp)
155 except IOError:
156 pass
Guido van Rossum3d209861997-12-09 16:10:31 +0000157
158 def get(self, section, option, raw=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000159 """Get an option value for a given section.
Guido van Rossum3d209861997-12-09 16:10:31 +0000160
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 All % interpolations are expanded in the return values, based
162 on the defaults passed into the constructor.
Guido van Rossum3d209861997-12-09 16:10:31 +0000163
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000164 The section DEFAULT is special.
165 """
166 try:
167 sectdict = self.__sections[section].copy()
168 except KeyError:
169 if section == DEFAULTSECT:
170 sectdict = {}
171 else:
172 raise NoSectionError(section)
173 d = self.__defaults.copy()
174 d.update(sectdict)
175 option = string.lower(option)
176 try:
177 rawval = d[option]
178 except KeyError:
179 raise NoOptionError(option, section)
180 # do the string interpolation
181 if raw:
182 return rawval
183 try:
184 return rawval % d
185 except KeyError, key:
186 raise InterpolationError(key, option, section)
Guido van Rossum3d209861997-12-09 16:10:31 +0000187
188 def __get(self, section, conv, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 return conv(self.get(section, option))
Guido van Rossum3d209861997-12-09 16:10:31 +0000190
191 def getint(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 return self.__get(section, string.atoi, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000193
194 def getfloat(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000195 return self.__get(section, string.atof, option)
Guido van Rossum3d209861997-12-09 16:10:31 +0000196
197 def getboolean(self, section, option):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 v = self.get(section, option)
199 val = string.atoi(v)
200 if val not in (0, 1):
201 raise ValueError, 'Not a boolean: %s' % v
202 return val
Guido van Rossum3d209861997-12-09 16:10:31 +0000203
204 def __read(self, fp):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 """Parse a sectioned setup file.
Guido van Rossum3d209861997-12-09 16:10:31 +0000206
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000207 The sections in setup file contains a title line at the top,
208 indicated by a name in square brackets (`[]'), plus key/value
209 options lines, indicated by `name: value' format lines.
210 Continuation are represented by an embedded newline then
211 leading whitespace. Blank lines, lines beginning with a '#',
212 and just about everything else is ignored.
213 """
214 cursect = None # None, or a dictionary
215 optname = None
216 lineno = 0
217 while 1:
218 line = fp.readline()
219 if not line:
220 break
221 lineno = lineno + 1
222 # comment or blank line?
223 if string.strip(line) == '' or line[0] in '#;':
224 continue
225 if string.lower(string.split(line)[0]) == 'rem' \
226 and line[0] == "r": # no leading whitespace
227 continue
228 # continuation line?
229 if line[0] in ' \t' and cursect <> None and optname:
230 value = string.strip(line)
231 if value:
232 cursect = cursect[optname] + '\n ' + value
233 # a section header?
234 elif secthead_cre.match(line) >= 0:
235 sectname = secthead_cre.group(1)
236 if self.__sections.has_key(sectname):
237 cursect = self.__sections[sectname]
238 elif sectname == DEFAULTSECT:
239 cursect = self.__defaults
240 else:
241 cursect = {'name': sectname}
242 self.__sections[sectname] = cursect
243 # So sections can't start with a continuation line.
244 optname = None
245 # an option line?
246 elif option_cre.match(line) >= 0:
247 optname, optval = option_cre.group(1, 3)
248 optname = string.lower(optname)
249 optval = string.strip(optval)
250 # allow empty values
251 if optval == '""':
252 optval = ''
253 cursect[optname] = optval
254 # an error
255 else:
256 print 'Error in %s at %d: %s', (fp.name, lineno, `line`)