cpython: Lib/ConfigParser.py annotate (original) (raw)

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

2

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

4 and followed by "name: value" entries, with continuations and such in

8614

5 the style of RFC 822.

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

6

8614

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.

9

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

11

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

13

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

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:

diff changeset

16

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

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:

diff changeset

19

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

20 class:

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

21

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

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:

diff changeset

24

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

25 methods:

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

26

9961

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

27 __init__(defaults=None)

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

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

diff changeset

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

diff changeset

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

diff changeset

31 it's value is the section's name.

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

32

9961

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

33 sections()

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

34 return all the configuration section names, sans DEFAULT

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

35

11370

41990bce023aAdded has_option(); fix bug in get() which botched interpolation if

Guido van Rossum guido@python.org

diff changeset

36 has_section(section)

41990bce023aAdded has_option(); fix bug in get() which botched interpolation if

Guido van Rossum guido@python.org

diff changeset

37 return whether the given section exists

41990bce023aAdded has_option(); fix bug in get() which botched interpolation if

Guido van Rossum guido@python.org

diff changeset

38

13600

39 has_option(section, option)

40 return whether the given option exists in the given section

41

9961

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

42 options(section)

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

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

diff changeset

44

10037

45 read(filenames)

11369

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.

49

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

11381

53 messages (if fp has no `name' attribute, the string `' is used).

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

54

9961

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

55 get(section, option, raw=0, vars=None)

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

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

diff changeset

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

diff changeset

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

diff changeset

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

diff changeset

60 contents override any pre-existing defaults.

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

61

9961

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

62 getint(section, options)

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

63 like get(), but convert value to an integer

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

64

9961

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

65 getfloat(section, options)

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

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

diff changeset

67

879e3491b661Re-format the module docstring and document the new get() argument.

Barry Warsaw barry@python.org

diff changeset

68 getboolean(section, options)

20261

56f17810534cApply modified SF patch 467580: ConfigParser.getboolean(): FALSE, TRUE.

Guido van Rossum guido@python.org

diff changeset

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

diff changeset

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

diff changeset

71 yes, on for 1). Returns 0 or 1.

13600

72

25461

73 items(section, raw=0, vars=None)

74 return a list of tuples with (name, value) for each option

75 in the section.

76

13600

77 remove_section(section)

15867

78 remove the given file section and all its options

13600

79

80 remove_option(section, option)

15867

81 remove the given option from the given section

13600

82

83 set(section, option, value)

84 set the given option

85

86 write(fp)

15867

87 write the configuration state in .ini format

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

88 """

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

89

8614

90 import re

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

91

16070

92 __all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",

93 "InterpolationError","InterpolationDepthError","ParsingError",

94 "MissingSectionHeaderError","ConfigParser",

25459

95 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]

16070

96

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

98

14899

99 MAX_INTERPOLATION_DEPTH = 10

100

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

101

15867

102

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

103 # exception classes

15501

104 class Error(Exception):

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

105 def __init__(self, msg=''):

8614

106 self._msg = msg

15501

107 Exception.__init__(self, msg)

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

108 def __repr__(self):

8614

109 return self._msg

15501

110 __str__ = __repr__

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

111

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

113 def __init__(self, section):

7755

114 Error.__init__(self, 'No section: %s' % section)

115 self.section = section

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

116

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

118 def __init__(self, section):

7755

119 Error.__init__(self, "Section %s already exists" % section)

120 self.section = section

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

121

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

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:

diff changeset

123 def __init__(self, option, section):

7755

124 Error.__init__(self, "No option `%s' in section: %s" %

125 (option, section))

126 self.option = option

127 self.section = section

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

128

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

129 class InterpolationError(Error):

8853

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

130 def __init__(self, reference, option, section, rawval):

7755

131 Error.__init__(self,

8853

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

132 "Bad value substitution:\n"

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

133 "\tsection: [%s]\n"

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

134 "\toption : %s\n"

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

135 "\tkey : %s\n"

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

136 "\trawval : %s\n"

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

137 % (section, option, reference, rawval))

7755

138 self.reference = reference

139 self.option = option

140 self.section = section

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

141

14899

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

8614

152

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 = []

158

159 def append(self, lineno, line):

160 self.errors.append((lineno, line))

161 self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)

162

14899

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

172

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

173

15867

174

25908

175 class RawConfigParser:

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

176 def __init__(self, defaults=None):

25908

177 self._sections = {}

7755

178 if defaults is None:

25908

179 self._defaults = {}

7755

180 else:

25908

181 self._defaults = defaults

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

182

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

183 def defaults(self):

25908

184 return self._defaults

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

185

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

186 def sections(self):

7755

187 """Return a list of section names, excluding [DEFAULT]"""

25908

188 # self._sections will never have [DEFAULT] in it

189 return self._sections.keys()

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

190

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

191 def add_section(self, section):

7755

192 """Create a new section in the configuration.

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

193

7755

194 Raise DuplicateSectionError if a section by the specified name

195 already exists.

196 """

25908

197 if section in self._sections:

7755

198 raise DuplicateSectionError(section)

25908

199 self._sections[section] = {}

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

200

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

201 def has_section(self, section):

7755

202 """Indicate whether the named section is present in the configuration.

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

203

7755

204 The DEFAULT section is not acknowledged.

205 """

25908

206 return section in self._sections

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

207

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

208 def options(self, section):

11370

41990bce023aAdded has_option(); fix bug in get() which botched interpolation if

Guido van Rossum guido@python.org

diff changeset

209 """Return a list of option names for the given section name."""

7755

210 try:

25908

211 opts = self._sections[section].copy()

7755

212 except KeyError:

213 raise NoSectionError(section)

25908

214 opts.update(self._defaults)

23620

215 if '__name__' in opts:

14899

216 del opts['__name__']

7755

217 return opts.keys()

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

218

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

219 def read(self, filenames):

11369

220 """Read and parse a filename or a list of filenames.

15867

221

11369

222 Files that cannot be opened are silently ignored; this is

11381

223 designed so that you can specify a list of potential

11369

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 """

23645

229 if isinstance(filenames, basestring):

7755

230 filenames = [filenames]

11369

231 for filename in filenames:

232 try:

233 fp = open(filename)

234 except IOError:

235 continue

25908

236 self._read(fp, filename)

11368

237 fp.close()

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

238

11369

239 def readfp(self, fp, filename=None):

240 """Like read() but the argument must be a file-like object.

241

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.

246

247 """

248 if filename is None:

249 try:

250 filename = fp.name

251 except AttributeError:

252 filename = ''

25908

253 self._read(fp, filename)

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

254

25908

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)

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

270

25908

271 def items(self, section):

7755

272 try:

25908

273 d2 = self._sections[section]

7755

274 except KeyError:

25459

275 if section != DEFAULTSECT:

7755

276 raise NoSectionError(section)

25916

277 d2 = {}

25908

278 d = self._defaults.copy()

279 d.update(d2)

25916

280 if "__name__" in d:

281 del d["__name__"]

25908

282 return d.items()

25461

283

25908

284 def _get(self, section, conv, option):

7755

285 return conv(self.get(section, option))

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

286

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

287 def getint(self, section, option):

25908

288 return self._get(section, int, option)

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

289

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

290 def getfloat(self, section, option):

25908

291 return self._get(section, float, option)

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

292

25459

293 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,

294 '0': False, 'no': False, 'false': False, 'off': False}

295

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

296 def getboolean(self, section, option):

20547

297 v = self.get(section, option)

25459

298 if v.lower() not in self._boolean_states:

7755

299 raise ValueError, 'Not a boolean: %s' % v

25459

300 return self._boolean_states[v.lower()]

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

301

11007

b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of

Guido van Rossum guido@python.org

diff changeset

302 def optionxform(self, optionstr):

16480

303 return optionstr.lower()

11007

b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of

Guido van Rossum guido@python.org

diff changeset

304

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

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

diff changeset

306 """Check for the existence of a given option in a given section."""

25459

307 if not section or section == DEFAULTSECT:

308 option = self.optionxform(option)

25908

309 return option in self._defaults

310 elif section not in self._sections:

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

311 return 0

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

312 else:

16771

b235160f1346Make sure ConfigParser uses .optionxform() consistently; this affects

Fred Drake fdrake@acm.org

diff changeset

313 option = self.optionxform(option)

25908

314 return (option in self._sections[section]

315 or option in self._defaults)

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

316

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

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

diff changeset

318 """Set an option."""

25459

319 if not section or section == DEFAULTSECT:

25908

320 sectdict = self._defaults

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

321 else:

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

322 try:

25908

323 sectdict = self._sections[section]

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

324 except KeyError:

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

325 raise NoSectionError(section)

25459

326 sectdict[self.optionxform(option)] = value

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

327

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

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

diff changeset

329 """Write an .ini-format representation of the configuration state."""

25908

330 if self._defaults:

25459

331 fp.write("[%s]\n" % DEFAULTSECT)

25908

332 for (key, value) in self._defaults.items():

22294

333 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

334 fp.write("\n")

25908

335 for section in self._sections:

25459

336 fp.write("[%s]\n" % section)

25908

337 for (key, value) in self._sections[section].items():

25459

338 if key != "__name__":

339 fp.write("%s = %s\n" %

340 (key, str(value).replace('\n', '\n\t')))

13521

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

341 fp.write("\n")

4dbc75c189bcGive ConfigParser the capability to set as well as read options, and to write

Eric S. Raymond esr@thyrsus.com

diff changeset

342

13650

3d6d218b673dSmall fixes by Petru Paler (patch #100946) checked in with esr's approval.

Thomas Wouters thomas@python.org

diff changeset

343 def remove_option(self, section, option):

13600

344 """Remove an option."""

25459

345 if not section or section == DEFAULTSECT:

25908

346 sectdict = self._defaults

13600

347 else:

348 try:

25908

349 sectdict = self._sections[section]

13600

350 except KeyError:

351 raise NoSectionError(section)

16771

b235160f1346Make sure ConfigParser uses .optionxform() consistently; this affects

Fred Drake fdrake@acm.org

diff changeset

352 option = self.optionxform(option)

23620

353 existed = option in sectdict

13600

354 if existed:

15479

355 del sectdict[option]

13600

356 return existed

357

13650

3d6d218b673dSmall fixes by Petru Paler (patch #100946) checked in with esr's approval.

Thomas Wouters thomas@python.org

diff changeset

358 def remove_section(self, section):

13600

359 """Remove a file section."""

25908

360 existed = section in self._sections

25459

361 if existed:

25908

362 del self._sections[section]

25459

363 return existed

13600

364

8614

365 #

25459

366 # Regular expressions for parsing section headers and options.

367 #

11007

b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of

Guido van Rossum guido@python.org

diff changeset

368 SECTCRE = re.compile(

8614

369 r'\[' # [

16594

9ef978c6f039Be much more permissive in what we accept in section names; there has been

Fred Drake fdrake@acm.org

diff changeset

370 r'(?P

[^]]+)' # very permissive!

8614

371 r'\]' # ]

372 )

11007

b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of

Guido van Rossum guido@python.org

diff changeset

373 OPTCRE = re.compile(

25462

374 r'(?P

25459

375 r'\s*(?P[:=])\s*' # any number of space/tab,

8614

376 # followed by separator

377 # (either : or =), followed

378 # by any # space/tab

379 r'(?P.*)$' # everything up to eol

380 )

381

25908

382 def _read(self, fp, fpname):

7755

383 """Parse a sectioned setup file.

6795

5b24cbb1f99bChecking in ConfigParser.py -- I don't see a reason why this can't be

Guido van Rossum guido@python.org

parents:

diff changeset

384

7755

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 """

8614

392 cursect = None # None, or a dictionary

7755

393 optname = None

394 lineno = 0

8614

395 e = None # None, or an exception

7755

396 while 1:

397 line = fp.readline()

398 if not line:

399 break

400 lineno = lineno + 1

401 # comment or blank line?

16480

402 if line.strip() == '' or line[0] in '#;':

7755

403 continue

25462

404 if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":

405 # no leading whitespace

7755

406 continue

407 # continuation line?

25459

408 if line[0].isspace() and cursect is not None and optname:

16480

409 value = line.strip()

7755

410 if value:

25459

411 cursect[optname] = "%s\n%s" % (cursect[optname], value)

8614

412 # a section header or option header?

413 else:

414 # is it a section header?

11007

b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of

Guido van Rossum guido@python.org

diff changeset

415 mo = self.SECTCRE.match(line)

8614

416 if mo:

417 sectname = mo.group('header')

25908

418 if sectname in self._sections:

419 cursect = self._sections[sectname]

8614

420 elif sectname == DEFAULTSECT:

25908

421 cursect = self._defaults

8614

422 else:

8853

bbe9d72bccdaTime machine experiment. Use '__name__' as the special key (always

Barry Warsaw barry@python.org

diff changeset

423 cursect = {'__name__': sectname}

25908

424 self._sections[sectname] = cursect

8614

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:

11369

429 raise MissingSectionHeaderError(fpname, lineno, `line`)

8614

430 # an option line?

7755

431 else:

11007

b9f55cc10ab3Patch suggested (and partially provided) by Lars Damerow: instead of

Guido van Rossum guido@python.org

diff changeset

432 mo = self.OPTCRE.match(line)

8614

433 if mo:

11873

434 optname, vi, optval = mo.group('option', 'vi', 'value')

11908

b975a056deb6allow comments beginning with ; in key: value as well as key = value

Jeremy Hylton jeremy@alum.mit.edu

diff changeset

435 if vi in ('=', ':') and ';' in optval:

11873

436 # ';' is a comment delimiter only if it follows

437 # a spacing character

16480

438 pos = optval.find(';')

25459

439 if pos != -1 and optval[pos-1].isspace():

11873

440 optval = optval[:pos]

16480

441 optval = optval.strip()

8614

442 # allow empty values

443 if optval == '""':

444 optval = ''

25462

445 optname = self.optionxform(optname.rstrip())

25459

446 cursect[optname] = optval

8614

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:

11369

453 e = ParsingError(fpname)

8614

454 e.append(lineno, `line`)

455 # if any parsing errors occurred, raise an exception

456 if e:

457 raise e

25908

458

459

460 class ConfigParser(RawConfigParser):

461

462 def get(self, section, option, raw=0, vars=None):

463 """Get an option value for a given section.

464

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.

470

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)

487

488 if raw:

489 return value

490 else:

491 return self._interpolate(section, option, value, d)

492

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.

496

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.

502

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)

25916

514 options = d.keys()

515 if "__name__" in options:

516 options.remove("__name__")

25908

517 if raw:

25916

518 for option in options:

25908

519 yield (option, d[option])

520 else:

25916

521 for option in options:

25908

522 yield (option,

523 self._interpolate(section, option, d[option], d))

524

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