PageRenderTime 55ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Python/system/ConfigParser.py

https://bitbucket.org/cwalther/moulscript-dlanor
Python | 616 lines | 614 code | 0 blank | 2 comment | 1 complexity | 0c8d19438b3391de5bec6f648c7239d2 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-3.0
  1. """Configuration file parser.
  2. A setup file consists of sections, lead by a "[section]" header,
  3. and followed by "name: value" entries, with continuations and such in
  4. the style of RFC 822.
  5. The option values can contain format strings which refer to other values in
  6. the same section, or values in a special [DEFAULT] section.
  7. For example:
  8. something: %(dir)s/whatever
  9. would resolve the "%(dir)s" to the value of dir. All reference
  10. expansions are done late, on demand.
  11. Intrinsic defaults can be specified by passing them into the
  12. ConfigParser constructor as a dictionary.
  13. class:
  14. ConfigParser -- responsible for parsing a list of
  15. configuration files, and managing the parsed database.
  16. methods:
  17. __init__(defaults=None)
  18. create the parser and specify a dictionary of intrinsic defaults. The
  19. keys must be strings, the values must be appropriate for %()s string
  20. interpolation. Note that `__name__' is always an intrinsic default;
  21. it's value is the section's name.
  22. sections()
  23. return all the configuration section names, sans DEFAULT
  24. has_section(section)
  25. return whether the given section exists
  26. has_option(section, option)
  27. return whether the given option exists in the given section
  28. options(section)
  29. return list of configuration options for the named section
  30. read(filenames)
  31. read and parse the list of named configuration files, given by
  32. name. A single filename is also allowed. Non-existing files
  33. are ignored.
  34. readfp(fp, filename=None)
  35. read and parse one configuration file, given as a file object.
  36. The filename defaults to fp.name; it is only used in error
  37. messages (if fp has no `name' attribute, the string `<???>' is used).
  38. get(section, option, raw=False, vars=None)
  39. return a string value for the named option. All % interpolations are
  40. expanded in the return values, based on the defaults passed into the
  41. constructor and the DEFAULT section. Additional substitutions may be
  42. provided using the `vars' argument, which must be a dictionary whose
  43. contents override any pre-existing defaults.
  44. getint(section, options)
  45. like get(), but convert value to an integer
  46. getfloat(section, options)
  47. like get(), but convert value to a float
  48. getboolean(section, options)
  49. like get(), but convert value to a boolean (currently case
  50. insensitively defined as 0, false, no, off for False, and 1, true,
  51. yes, on for True). Returns False or True.
  52. items(section, raw=False, vars=None)
  53. return a list of tuples with (name, value) for each option
  54. in the section.
  55. remove_section(section)
  56. remove the given file section and all its options
  57. remove_option(section, option)
  58. remove the given option from the given section
  59. set(section, option, value)
  60. set the given option
  61. write(fp)
  62. write the configuration state in .ini format
  63. """
  64. import re
  65. __all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
  66. "InterpolationError", "InterpolationDepthError",
  67. "InterpolationSyntaxError", "ParsingError",
  68. "MissingSectionHeaderError", "ConfigParser", "SafeConfigParser",
  69. "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
  70. DEFAULTSECT = "DEFAULT"
  71. MAX_INTERPOLATION_DEPTH = 10
  72. # exception classes
  73. class Error(Exception):
  74. """Base class for ConfigParser exceptions."""
  75. def __init__(self, msg=''):
  76. self.message = msg
  77. Exception.__init__(self, msg)
  78. def __repr__(self):
  79. return self.message
  80. __str__ = __repr__
  81. class NoSectionError(Error):
  82. """Raised when no section matches a requested option."""
  83. def __init__(self, section):
  84. Error.__init__(self, 'No section: ' + `section`)
  85. self.section = section
  86. class DuplicateSectionError(Error):
  87. """Raised when a section is multiply-created."""
  88. def __init__(self, section):
  89. Error.__init__(self, "Section %r already exists" % section)
  90. self.section = section
  91. class NoOptionError(Error):
  92. """A requested option was not found."""
  93. def __init__(self, option, section):
  94. Error.__init__(self, "No option %r in section: %r" %
  95. (option, section))
  96. self.option = option
  97. self.section = section
  98. class InterpolationError(Error):
  99. """Base class for interpolation-related exceptions."""
  100. def __init__(self, option, section, msg):
  101. Error.__init__(self, msg)
  102. self.option = option
  103. self.section = section
  104. class InterpolationMissingOptionError(InterpolationError):
  105. """A string substitution required a setting which was not available."""
  106. def __init__(self, option, section, rawval, reference):
  107. msg = ("Bad value substitution:\n"
  108. "\tsection: [%s]\n"
  109. "\toption : %s\n"
  110. "\tkey : %s\n"
  111. "\trawval : %s\n"
  112. % (section, option, reference, rawval))
  113. InterpolationError.__init__(self, option, section, msg)
  114. self.reference = reference
  115. class InterpolationSyntaxError(InterpolationError):
  116. """Raised when the source text into which substitutions are made
  117. does not conform to the required syntax."""
  118. class InterpolationDepthError(InterpolationError):
  119. """Raised when substitutions are nested too deeply."""
  120. def __init__(self, option, section, rawval):
  121. msg = ("Value interpolation too deeply recursive:\n"
  122. "\tsection: [%s]\n"
  123. "\toption : %s\n"
  124. "\trawval : %s\n"
  125. % (section, option, rawval))
  126. InterpolationError.__init__(self, option, section, msg)
  127. class ParsingError(Error):
  128. """Raised when a configuration file does not follow legal syntax."""
  129. def __init__(self, filename):
  130. Error.__init__(self, 'File contains parsing errors: %s' % filename)
  131. self.filename = filename
  132. self.errors = []
  133. def append(self, lineno, line):
  134. self.errors.append((lineno, line))
  135. self.message += '\n\t[line %2d]: %s' % (lineno, line)
  136. class MissingSectionHeaderError(ParsingError):
  137. """Raised when a key-value pair is found before any section header."""
  138. def __init__(self, filename, lineno, line):
  139. Error.__init__(
  140. self,
  141. 'File contains no section headers.\nfile: %s, line: %d\n%s' %
  142. (filename, lineno, line))
  143. self.filename = filename
  144. self.lineno = lineno
  145. self.line = line
  146. class RawConfigParser:
  147. def __init__(self, defaults=None):
  148. self._sections = {}
  149. if defaults is None:
  150. self._defaults = {}
  151. else:
  152. self._defaults = defaults
  153. def defaults(self):
  154. return self._defaults
  155. def sections(self):
  156. """Return a list of section names, excluding [DEFAULT]"""
  157. # self._sections will never have [DEFAULT] in it
  158. return self._sections.keys()
  159. def add_section(self, section):
  160. """Create a new section in the configuration.
  161. Raise DuplicateSectionError if a section by the specified name
  162. already exists.
  163. """
  164. if section in self._sections:
  165. raise DuplicateSectionError(section)
  166. self._sections[section] = {}
  167. def has_section(self, section):
  168. """Indicate whether the named section is present in the configuration.
  169. The DEFAULT section is not acknowledged.
  170. """
  171. return section in self._sections
  172. def options(self, section):
  173. """Return a list of option names for the given section name."""
  174. try:
  175. opts = self._sections[section].copy()
  176. except KeyError:
  177. raise NoSectionError(section)
  178. opts.update(self._defaults)
  179. if '__name__' in opts:
  180. del opts['__name__']
  181. return opts.keys()
  182. def read(self, filenames):
  183. """Read and parse a filename or a list of filenames.
  184. Files that cannot be opened are silently ignored; this is
  185. designed so that you can specify a list of potential
  186. configuration file locations (e.g. current directory, user's
  187. home directory, systemwide directory), and all existing
  188. configuration files in the list will be read. A single
  189. filename may also be given.
  190. """
  191. if isinstance(filenames, basestring):
  192. filenames = [filenames]
  193. for filename in filenames:
  194. try:
  195. fp = open(filename)
  196. except IOError:
  197. continue
  198. self._read(fp, filename)
  199. fp.close()
  200. def readfp(self, fp, filename=None):
  201. """Like read() but the argument must be a file-like object.
  202. The `fp' argument must have a `readline' method. Optional
  203. second argument is the `filename', which if not given, is
  204. taken from fp.name. If fp has no `name' attribute, `<???>' is
  205. used.
  206. """
  207. if filename is None:
  208. try:
  209. filename = fp.name
  210. except AttributeError:
  211. filename = '<???>'
  212. self._read(fp, filename)
  213. def get(self, section, option):
  214. opt = self.optionxform(option)
  215. if section not in self._sections:
  216. if section != DEFAULTSECT:
  217. raise NoSectionError(section)
  218. if opt in self._defaults:
  219. return self._defaults[opt]
  220. else:
  221. raise NoOptionError(option, section)
  222. elif opt in self._sections[section]:
  223. return self._sections[section][opt]
  224. elif opt in self._defaults:
  225. return self._defaults[opt]
  226. else:
  227. raise NoOptionError(option, section)
  228. def items(self, section):
  229. try:
  230. d2 = self._sections[section]
  231. except KeyError:
  232. if section != DEFAULTSECT:
  233. raise NoSectionError(section)
  234. d2 = {}
  235. d = self._defaults.copy()
  236. d.update(d2)
  237. if "__name__" in d:
  238. del d["__name__"]
  239. return d.items()
  240. def _get(self, section, conv, option):
  241. return conv(self.get(section, option))
  242. def getint(self, section, option):
  243. return self._get(section, int, option)
  244. def getfloat(self, section, option):
  245. return self._get(section, float, option)
  246. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  247. '0': False, 'no': False, 'false': False, 'off': False}
  248. def getboolean(self, section, option):
  249. v = self.get(section, option)
  250. if v.lower() not in self._boolean_states:
  251. raise ValueError, 'Not a boolean: %s' % v
  252. return self._boolean_states[v.lower()]
  253. def optionxform(self, optionstr):
  254. return optionstr.lower()
  255. def has_option(self, section, option):
  256. """Check for the existence of a given option in a given section."""
  257. if not section or section == DEFAULTSECT:
  258. option = self.optionxform(option)
  259. return option in self._defaults
  260. elif section not in self._sections:
  261. return False
  262. else:
  263. option = self.optionxform(option)
  264. return (option in self._sections[section]
  265. or option in self._defaults)
  266. def set(self, section, option, value):
  267. """Set an option."""
  268. if not section or section == DEFAULTSECT:
  269. sectdict = self._defaults
  270. else:
  271. try:
  272. sectdict = self._sections[section]
  273. except KeyError:
  274. raise NoSectionError(section)
  275. sectdict[self.optionxform(option)] = value
  276. def write(self, fp):
  277. """Write an .ini-format representation of the configuration state."""
  278. if self._defaults:
  279. fp.write("[%s]\n" % DEFAULTSECT)
  280. for (key, value) in self._defaults.items():
  281. fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  282. fp.write("\n")
  283. for section in self._sections:
  284. fp.write("[%s]\n" % section)
  285. for (key, value) in self._sections[section].items():
  286. if key != "__name__":
  287. fp.write("%s = %s\n" %
  288. (key, str(value).replace('\n', '\n\t')))
  289. fp.write("\n")
  290. def remove_option(self, section, option):
  291. """Remove an option."""
  292. if not section or section == DEFAULTSECT:
  293. sectdict = self._defaults
  294. else:
  295. try:
  296. sectdict = self._sections[section]
  297. except KeyError:
  298. raise NoSectionError(section)
  299. option = self.optionxform(option)
  300. existed = option in sectdict
  301. if existed:
  302. del sectdict[option]
  303. return existed
  304. def remove_section(self, section):
  305. """Remove a file section."""
  306. existed = section in self._sections
  307. if existed:
  308. del self._sections[section]
  309. return existed
  310. #
  311. # Regular expressions for parsing section headers and options.
  312. #
  313. SECTCRE = re.compile(
  314. r'\[' # [
  315. r'(?P<header>[^]]+)' # very permissive!
  316. r'\]' # ]
  317. )
  318. OPTCRE = re.compile(
  319. r'(?P<option>[^:=\s][^:=]*)' # very permissive!
  320. r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
  321. # followed by separator
  322. # (either : or =), followed
  323. # by any # space/tab
  324. r'(?P<value>.*)$' # everything up to eol
  325. )
  326. def _read(self, fp, fpname):
  327. """Parse a sectioned setup file.
  328. The sections in setup file contains a title line at the top,
  329. indicated by a name in square brackets (`[]'), plus key/value
  330. options lines, indicated by `name: value' format lines.
  331. Continuations are represented by an embedded newline then
  332. leading whitespace. Blank lines, lines beginning with a '#',
  333. and just about everything else are ignored.
  334. """
  335. cursect = None # None, or a dictionary
  336. optname = None
  337. lineno = 0
  338. e = None # None, or an exception
  339. while True:
  340. line = fp.readline()
  341. if not line:
  342. break
  343. lineno = lineno + 1
  344. # comment or blank line?
  345. if line.strip() == '' or line[0] in '#;':
  346. continue
  347. if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
  348. # no leading whitespace
  349. continue
  350. # continuation line?
  351. if line[0].isspace() and cursect is not None and optname:
  352. value = line.strip()
  353. if value:
  354. cursect[optname] = "%s\n%s" % (cursect[optname], value)
  355. # a section header or option header?
  356. else:
  357. # is it a section header?
  358. mo = self.SECTCRE.match(line)
  359. if mo:
  360. sectname = mo.group('header')
  361. if sectname in self._sections:
  362. cursect = self._sections[sectname]
  363. elif sectname == DEFAULTSECT:
  364. cursect = self._defaults
  365. else:
  366. cursect = {'__name__': sectname}
  367. self._sections[sectname] = cursect
  368. # So sections can't start with a continuation line
  369. optname = None
  370. # no section header in the file?
  371. elif cursect is None:
  372. raise MissingSectionHeaderError(fpname, lineno, `line`)
  373. # an option line?
  374. else:
  375. mo = self.OPTCRE.match(line)
  376. if mo:
  377. optname, vi, optval = mo.group('option', 'vi', 'value')
  378. if vi in ('=', ':') and ';' in optval:
  379. # ';' is a comment delimiter only if it follows
  380. # a spacing character
  381. pos = optval.find(';')
  382. if pos != -1 and optval[pos-1].isspace():
  383. optval = optval[:pos]
  384. optval = optval.strip()
  385. # allow empty values
  386. if optval == '""':
  387. optval = ''
  388. optname = self.optionxform(optname.rstrip())
  389. cursect[optname] = optval
  390. else:
  391. # a non-fatal parsing error occurred. set up the
  392. # exception but keep going. the exception will be
  393. # raised at the end of the file and will contain a
  394. # list of all bogus lines
  395. if not e:
  396. e = ParsingError(fpname)
  397. e.append(lineno, `line`)
  398. # if any parsing errors occurred, raise an exception
  399. if e:
  400. raise e
  401. class ConfigParser(RawConfigParser):
  402. def get(self, section, option, raw=False, vars=None):
  403. """Get an option value for a given section.
  404. All % interpolations are expanded in the return values, based on the
  405. defaults passed into the constructor, unless the optional argument
  406. `raw' is true. Additional substitutions may be provided using the
  407. `vars' argument, which must be a dictionary whose contents overrides
  408. any pre-existing defaults.
  409. The section DEFAULT is special.
  410. """
  411. d = self._defaults.copy()
  412. try:
  413. d.update(self._sections[section])
  414. except KeyError:
  415. if section != DEFAULTSECT:
  416. raise NoSectionError(section)
  417. # Update with the entry specific variables
  418. if vars is not None:
  419. d.update(vars)
  420. option = self.optionxform(option)
  421. try:
  422. value = d[option]
  423. except KeyError:
  424. raise NoOptionError(option, section)
  425. if raw:
  426. return value
  427. else:
  428. return self._interpolate(section, option, value, d)
  429. def items(self, section, raw=False, vars=None):
  430. """Return a list of tuples with (name, value) for each option
  431. in the section.
  432. All % interpolations are expanded in the return values, based on the
  433. defaults passed into the constructor, unless the optional argument
  434. `raw' is true. Additional substitutions may be provided using the
  435. `vars' argument, which must be a dictionary whose contents overrides
  436. any pre-existing defaults.
  437. The section DEFAULT is special.
  438. """
  439. d = self._defaults.copy()
  440. try:
  441. d.update(self._sections[section])
  442. except KeyError:
  443. if section != DEFAULTSECT:
  444. raise NoSectionError(section)
  445. # Update with the entry specific variables
  446. if vars:
  447. d.update(vars)
  448. options = d.keys()
  449. if "__name__" in options:
  450. options.remove("__name__")
  451. if raw:
  452. return [(option, d[option])
  453. for option in options]
  454. else:
  455. return [(option, self._interpolate(section, option, d[option], d))
  456. for option in options]
  457. def _interpolate(self, section, option, rawval, vars):
  458. # do the string interpolation
  459. value = rawval
  460. depth = MAX_INTERPOLATION_DEPTH
  461. while depth: # Loop through this until it's done
  462. depth -= 1
  463. if value.find("%(") != -1:
  464. try:
  465. value = value % vars
  466. except KeyError, e:
  467. raise InterpolationMissingOptionError(
  468. option, section, rawval, e[0])
  469. else:
  470. break
  471. if value.find("%(") != -1:
  472. raise InterpolationDepthError(option, section, rawval)
  473. return value
  474. class SafeConfigParser(ConfigParser):
  475. def _interpolate(self, section, option, rawval, vars):
  476. # do the string interpolation
  477. L = []
  478. self._interpolate_some(option, L, rawval, section, vars, 1)
  479. return ''.join(L)
  480. _interpvar_match = re.compile(r"%\(([^)]+)\)s").match
  481. def _interpolate_some(self, option, accum, rest, section, map, depth):
  482. if depth > MAX_INTERPOLATION_DEPTH:
  483. raise InterpolationDepthError(option, section, rest)
  484. while rest:
  485. p = rest.find("%")
  486. if p < 0:
  487. accum.append(rest)
  488. return
  489. if p > 0:
  490. accum.append(rest[:p])
  491. rest = rest[p:]
  492. # p is no longer used
  493. c = rest[1:2]
  494. if c == "%":
  495. accum.append("%")
  496. rest = rest[2:]
  497. elif c == "(":
  498. m = self._interpvar_match(rest)
  499. if m is None:
  500. raise InterpolationSyntaxError(option, section,
  501. "bad interpolation variable reference %r" % rest)
  502. var = m.group(1)
  503. rest = rest[m.end():]
  504. try:
  505. v = map[var]
  506. except KeyError:
  507. raise InterpolationMissingOptionError(
  508. option, section, rest, var)
  509. if "%" in v:
  510. self._interpolate_some(option, accum, v,
  511. section, map, depth + 1)
  512. else:
  513. accum.append(v)
  514. else:
  515. raise InterpolationSyntaxError(
  516. option, section,
  517. "'%' must be followed by '%' or '(', found: " + `rest`)