PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/ConfigParser.py

https://bitbucket.org/bwesterb/pypy
Python | 753 lines | 751 code | 0 blank | 2 comment | 1 complexity | c1a16e098a25d74be9d7c781e2f16ccd MD5 | raw file
  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. its 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. Return list of successfully read files.
  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. try:
  65. from collections import OrderedDict as _default_dict
  66. except ImportError:
  67. # fallback for setup.py which hasn't yet built _collections
  68. _default_dict = dict
  69. import re
  70. __all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",
  71. "InterpolationError", "InterpolationDepthError",
  72. "InterpolationSyntaxError", "ParsingError",
  73. "MissingSectionHeaderError",
  74. "ConfigParser", "SafeConfigParser", "RawConfigParser",
  75. "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
  76. DEFAULTSECT = "DEFAULT"
  77. MAX_INTERPOLATION_DEPTH = 10
  78. # exception classes
  79. class Error(Exception):
  80. """Base class for ConfigParser exceptions."""
  81. def _get_message(self):
  82. """Getter for 'message'; needed only to override deprecation in
  83. BaseException."""
  84. return self.__message
  85. def _set_message(self, value):
  86. """Setter for 'message'; needed only to override deprecation in
  87. BaseException."""
  88. self.__message = value
  89. # BaseException.message has been deprecated since Python 2.6. To prevent
  90. # DeprecationWarning from popping up over this pre-existing attribute, use
  91. # a new property that takes lookup precedence.
  92. message = property(_get_message, _set_message)
  93. def __init__(self, msg=''):
  94. self.message = msg
  95. Exception.__init__(self, msg)
  96. def __repr__(self):
  97. return self.message
  98. __str__ = __repr__
  99. class NoSectionError(Error):
  100. """Raised when no section matches a requested option."""
  101. def __init__(self, section):
  102. Error.__init__(self, 'No section: %r' % (section,))
  103. self.section = section
  104. self.args = (section, )
  105. class DuplicateSectionError(Error):
  106. """Raised when a section is multiply-created."""
  107. def __init__(self, section):
  108. Error.__init__(self, "Section %r already exists" % section)
  109. self.section = section
  110. self.args = (section, )
  111. class NoOptionError(Error):
  112. """A requested option was not found."""
  113. def __init__(self, option, section):
  114. Error.__init__(self, "No option %r in section: %r" %
  115. (option, section))
  116. self.option = option
  117. self.section = section
  118. self.args = (option, section)
  119. class InterpolationError(Error):
  120. """Base class for interpolation-related exceptions."""
  121. def __init__(self, option, section, msg):
  122. Error.__init__(self, msg)
  123. self.option = option
  124. self.section = section
  125. self.args = (option, section, msg)
  126. class InterpolationMissingOptionError(InterpolationError):
  127. """A string substitution required a setting which was not available."""
  128. def __init__(self, option, section, rawval, reference):
  129. msg = ("Bad value substitution:\n"
  130. "\tsection: [%s]\n"
  131. "\toption : %s\n"
  132. "\tkey : %s\n"
  133. "\trawval : %s\n"
  134. % (section, option, reference, rawval))
  135. InterpolationError.__init__(self, option, section, msg)
  136. self.reference = reference
  137. self.args = (option, section, rawval, reference)
  138. class InterpolationSyntaxError(InterpolationError):
  139. """Raised when the source text into which substitutions are made
  140. does not conform to the required syntax."""
  141. class InterpolationDepthError(InterpolationError):
  142. """Raised when substitutions are nested too deeply."""
  143. def __init__(self, option, section, rawval):
  144. msg = ("Value interpolation too deeply recursive:\n"
  145. "\tsection: [%s]\n"
  146. "\toption : %s\n"
  147. "\trawval : %s\n"
  148. % (section, option, rawval))
  149. InterpolationError.__init__(self, option, section, msg)
  150. self.args = (option, section, rawval)
  151. class ParsingError(Error):
  152. """Raised when a configuration file does not follow legal syntax."""
  153. def __init__(self, filename):
  154. Error.__init__(self, 'File contains parsing errors: %s' % filename)
  155. self.filename = filename
  156. self.errors = []
  157. self.args = (filename, )
  158. def append(self, lineno, line):
  159. self.errors.append((lineno, line))
  160. self.message += '\n\t[line %2d]: %s' % (lineno, line)
  161. class MissingSectionHeaderError(ParsingError):
  162. """Raised when a key-value pair is found before any section header."""
  163. def __init__(self, filename, lineno, line):
  164. Error.__init__(
  165. self,
  166. 'File contains no section headers.\nfile: %s, line: %d\n%r' %
  167. (filename, lineno, line))
  168. self.filename = filename
  169. self.lineno = lineno
  170. self.line = line
  171. self.args = (filename, lineno, line)
  172. class RawConfigParser:
  173. def __init__(self, defaults=None, dict_type=_default_dict,
  174. allow_no_value=False):
  175. self._dict = dict_type
  176. self._sections = self._dict()
  177. self._defaults = self._dict()
  178. if allow_no_value:
  179. self._optcre = self.OPTCRE_NV
  180. else:
  181. self._optcre = self.OPTCRE
  182. if defaults:
  183. for key, value in defaults.items():
  184. self._defaults[self.optionxform(key)] = value
  185. def defaults(self):
  186. return self._defaults
  187. def sections(self):
  188. """Return a list of section names, excluding [DEFAULT]"""
  189. # self._sections will never have [DEFAULT] in it
  190. return self._sections.keys()
  191. def add_section(self, section):
  192. """Create a new section in the configuration.
  193. Raise DuplicateSectionError if a section by the specified name
  194. already exists. Raise ValueError if name is DEFAULT or any of it's
  195. case-insensitive variants.
  196. """
  197. if section.lower() == "default":
  198. raise ValueError, 'Invalid section name: %s' % section
  199. if section in self._sections:
  200. raise DuplicateSectionError(section)
  201. self._sections[section] = self._dict()
  202. def has_section(self, section):
  203. """Indicate whether the named section is present in the configuration.
  204. The DEFAULT section is not acknowledged.
  205. """
  206. return section in self._sections
  207. def options(self, section):
  208. """Return a list of option names for the given section name."""
  209. try:
  210. opts = self._sections[section].copy()
  211. except KeyError:
  212. raise NoSectionError(section)
  213. opts.update(self._defaults)
  214. if '__name__' in opts:
  215. del opts['__name__']
  216. return opts.keys()
  217. def read(self, filenames):
  218. """Read and parse a filename or a list of filenames.
  219. Files that cannot be opened are silently ignored; this is
  220. designed so that you can specify a list of potential
  221. configuration file locations (e.g. current directory, user's
  222. home directory, systemwide directory), and all existing
  223. configuration files in the list will be read. A single
  224. filename may also be given.
  225. Return list of successfully read files.
  226. """
  227. if isinstance(filenames, basestring):
  228. filenames = [filenames]
  229. read_ok = []
  230. for filename in filenames:
  231. try:
  232. fp = open(filename)
  233. except IOError:
  234. continue
  235. self._read(fp, filename)
  236. fp.close()
  237. read_ok.append(filename)
  238. return read_ok
  239. def readfp(self, fp, filename=None):
  240. """Like read() but the argument must be a file-like object.
  241. The `fp' argument must have a `readline' method. Optional
  242. second argument is the `filename', which if not given, is
  243. taken from fp.name. If fp has no `name' attribute, `<???>' is
  244. used.
  245. """
  246. if filename is None:
  247. try:
  248. filename = fp.name
  249. except AttributeError:
  250. filename = '<???>'
  251. self._read(fp, filename)
  252. def get(self, section, option):
  253. opt = self.optionxform(option)
  254. if section not in self._sections:
  255. if section != DEFAULTSECT:
  256. raise NoSectionError(section)
  257. if opt in self._defaults:
  258. return self._defaults[opt]
  259. else:
  260. raise NoOptionError(option, section)
  261. elif opt in self._sections[section]:
  262. return self._sections[section][opt]
  263. elif opt in self._defaults:
  264. return self._defaults[opt]
  265. else:
  266. raise NoOptionError(option, section)
  267. def items(self, section):
  268. try:
  269. d2 = self._sections[section]
  270. except KeyError:
  271. if section != DEFAULTSECT:
  272. raise NoSectionError(section)
  273. d2 = self._dict()
  274. d = self._defaults.copy()
  275. d.update(d2)
  276. if "__name__" in d:
  277. del d["__name__"]
  278. return d.items()
  279. def _get(self, section, conv, option):
  280. return conv(self.get(section, option))
  281. def getint(self, section, option):
  282. return self._get(section, int, option)
  283. def getfloat(self, section, option):
  284. return self._get(section, float, option)
  285. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  286. '0': False, 'no': False, 'false': False, 'off': False}
  287. def getboolean(self, section, option):
  288. v = self.get(section, option)
  289. if v.lower() not in self._boolean_states:
  290. raise ValueError, 'Not a boolean: %s' % v
  291. return self._boolean_states[v.lower()]
  292. def optionxform(self, optionstr):
  293. return optionstr.lower()
  294. def has_option(self, section, option):
  295. """Check for the existence of a given option in a given section."""
  296. if not section or section == DEFAULTSECT:
  297. option = self.optionxform(option)
  298. return option in self._defaults
  299. elif section not in self._sections:
  300. return False
  301. else:
  302. option = self.optionxform(option)
  303. return (option in self._sections[section]
  304. or option in self._defaults)
  305. def set(self, section, option, value=None):
  306. """Set an option."""
  307. if not section or section == DEFAULTSECT:
  308. sectdict = self._defaults
  309. else:
  310. try:
  311. sectdict = self._sections[section]
  312. except KeyError:
  313. raise NoSectionError(section)
  314. sectdict[self.optionxform(option)] = value
  315. def write(self, fp):
  316. """Write an .ini-format representation of the configuration state."""
  317. if self._defaults:
  318. fp.write("[%s]\n" % DEFAULTSECT)
  319. for (key, value) in self._defaults.items():
  320. fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  321. fp.write("\n")
  322. for section in self._sections:
  323. fp.write("[%s]\n" % section)
  324. for (key, value) in self._sections[section].items():
  325. if key == "__name__":
  326. continue
  327. if (value is not None) or (self._optcre == self.OPTCRE):
  328. key = " = ".join((key, str(value).replace('\n', '\n\t')))
  329. fp.write("%s\n" % (key))
  330. fp.write("\n")
  331. def remove_option(self, section, option):
  332. """Remove an option."""
  333. if not section or section == DEFAULTSECT:
  334. sectdict = self._defaults
  335. else:
  336. try:
  337. sectdict = self._sections[section]
  338. except KeyError:
  339. raise NoSectionError(section)
  340. option = self.optionxform(option)
  341. existed = option in sectdict
  342. if existed:
  343. del sectdict[option]
  344. return existed
  345. def remove_section(self, section):
  346. """Remove a file section."""
  347. existed = section in self._sections
  348. if existed:
  349. del self._sections[section]
  350. return existed
  351. #
  352. # Regular expressions for parsing section headers and options.
  353. #
  354. SECTCRE = re.compile(
  355. r'\[' # [
  356. r'(?P<header>[^]]+)' # very permissive!
  357. r'\]' # ]
  358. )
  359. OPTCRE = re.compile(
  360. r'(?P<option>[^:=\s][^:=]*)' # very permissive!
  361. r'\s*(?P<vi>[:=])\s*' # any number of space/tab,
  362. # followed by separator
  363. # (either : or =), followed
  364. # by any # space/tab
  365. r'(?P<value>.*)$' # everything up to eol
  366. )
  367. OPTCRE_NV = re.compile(
  368. r'(?P<option>[^:=\s][^:=]*)' # very permissive!
  369. r'\s*(?:' # any number of space/tab,
  370. r'(?P<vi>[:=])\s*' # optionally followed by
  371. # separator (either : or
  372. # =), followed by any #
  373. # space/tab
  374. r'(?P<value>.*))?$' # everything up to eol
  375. )
  376. def _read(self, fp, fpname):
  377. """Parse a sectioned setup file.
  378. The sections in setup file contains a title line at the top,
  379. indicated by a name in square brackets (`[]'), plus key/value
  380. options lines, indicated by `name: value' format lines.
  381. Continuations are represented by an embedded newline then
  382. leading whitespace. Blank lines, lines beginning with a '#',
  383. and just about everything else are ignored.
  384. """
  385. cursect = None # None, or a dictionary
  386. optname = None
  387. lineno = 0
  388. e = None # None, or an exception
  389. while True:
  390. line = fp.readline()
  391. if not line:
  392. break
  393. lineno = lineno + 1
  394. # comment or blank line?
  395. if line.strip() == '' or line[0] in '#;':
  396. continue
  397. if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":
  398. # no leading whitespace
  399. continue
  400. # continuation line?
  401. if line[0].isspace() and cursect is not None and optname:
  402. value = line.strip()
  403. if value:
  404. cursect[optname].append(value)
  405. # a section header or option header?
  406. else:
  407. # is it a section header?
  408. mo = self.SECTCRE.match(line)
  409. if mo:
  410. sectname = mo.group('header')
  411. if sectname in self._sections:
  412. cursect = self._sections[sectname]
  413. elif sectname == DEFAULTSECT:
  414. cursect = self._defaults
  415. else:
  416. cursect = self._dict()
  417. cursect['__name__'] = sectname
  418. self._sections[sectname] = cursect
  419. # So sections can't start with a continuation line
  420. optname = None
  421. # no section header in the file?
  422. elif cursect is None:
  423. raise MissingSectionHeaderError(fpname, lineno, line)
  424. # an option line?
  425. else:
  426. mo = self._optcre.match(line)
  427. if mo:
  428. optname, vi, optval = mo.group('option', 'vi', 'value')
  429. optname = self.optionxform(optname.rstrip())
  430. # This check is fine because the OPTCRE cannot
  431. # match if it would set optval to None
  432. if optval is not None:
  433. if vi in ('=', ':') and ';' in optval:
  434. # ';' is a comment delimiter only if it follows
  435. # a spacing character
  436. pos = optval.find(';')
  437. if pos != -1 and optval[pos-1].isspace():
  438. optval = optval[:pos]
  439. optval = optval.strip()
  440. # allow empty values
  441. if optval == '""':
  442. optval = ''
  443. cursect[optname] = [optval]
  444. else:
  445. # valueless option handling
  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, repr(line))
  455. # if any parsing errors occurred, raise an exception
  456. if e:
  457. raise e
  458. # join the multi-line values collected while reading
  459. all_sections = [self._defaults]
  460. all_sections.extend(self._sections.values())
  461. for options in all_sections:
  462. for name, val in options.items():
  463. if isinstance(val, list):
  464. options[name] = '\n'.join(val)
  465. import UserDict as _UserDict
  466. class _Chainmap(_UserDict.DictMixin):
  467. """Combine multiple mappings for successive lookups.
  468. For example, to emulate Python's normal lookup sequence:
  469. import __builtin__
  470. pylookup = _Chainmap(locals(), globals(), vars(__builtin__))
  471. """
  472. def __init__(self, *maps):
  473. self._maps = maps
  474. def __getitem__(self, key):
  475. for mapping in self._maps:
  476. try:
  477. return mapping[key]
  478. except KeyError:
  479. pass
  480. raise KeyError(key)
  481. def keys(self):
  482. result = []
  483. seen = set()
  484. for mapping in self._maps:
  485. for key in mapping:
  486. if key not in seen:
  487. result.append(key)
  488. seen.add(key)
  489. return result
  490. class ConfigParser(RawConfigParser):
  491. def get(self, section, option, raw=False, vars=None):
  492. """Get an option value for a given section.
  493. If `vars' is provided, it must be a dictionary. The option is looked up
  494. in `vars' (if provided), `section', and in `defaults' in that order.
  495. All % interpolations are expanded in the return values, unless the
  496. optional argument `raw' is true. Values for interpolation keys are
  497. looked up in the same manner as the option.
  498. The section DEFAULT is special.
  499. """
  500. sectiondict = {}
  501. try:
  502. sectiondict = self._sections[section]
  503. except KeyError:
  504. if section != DEFAULTSECT:
  505. raise NoSectionError(section)
  506. # Update with the entry specific variables
  507. vardict = {}
  508. if vars:
  509. for key, value in vars.items():
  510. vardict[self.optionxform(key)] = value
  511. d = _Chainmap(vardict, sectiondict, self._defaults)
  512. option = self.optionxform(option)
  513. try:
  514. value = d[option]
  515. except KeyError:
  516. raise NoOptionError(option, section)
  517. if raw or value is None:
  518. return value
  519. else:
  520. return self._interpolate(section, option, value, d)
  521. def items(self, section, raw=False, vars=None):
  522. """Return a list of tuples with (name, value) for each option
  523. in the section.
  524. All % interpolations are expanded in the return values, based on the
  525. defaults passed into the constructor, unless the optional argument
  526. `raw' is true. Additional substitutions may be provided using the
  527. `vars' argument, which must be a dictionary whose contents overrides
  528. any pre-existing defaults.
  529. The section DEFAULT is special.
  530. """
  531. d = self._defaults.copy()
  532. try:
  533. d.update(self._sections[section])
  534. except KeyError:
  535. if section != DEFAULTSECT:
  536. raise NoSectionError(section)
  537. # Update with the entry specific variables
  538. if vars:
  539. for key, value in vars.items():
  540. d[self.optionxform(key)] = value
  541. options = d.keys()
  542. if "__name__" in options:
  543. options.remove("__name__")
  544. if raw:
  545. return [(option, d[option])
  546. for option in options]
  547. else:
  548. return [(option, self._interpolate(section, option, d[option], d))
  549. for option in options]
  550. def _interpolate(self, section, option, rawval, vars):
  551. # do the string interpolation
  552. value = rawval
  553. depth = MAX_INTERPOLATION_DEPTH
  554. while depth: # Loop through this until it's done
  555. depth -= 1
  556. if value and "%(" in value:
  557. value = self._KEYCRE.sub(self._interpolation_replace, value)
  558. try:
  559. value = value % vars
  560. except KeyError, e:
  561. raise InterpolationMissingOptionError(
  562. option, section, rawval, e.args[0])
  563. else:
  564. break
  565. if value and "%(" in value:
  566. raise InterpolationDepthError(option, section, rawval)
  567. return value
  568. _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
  569. def _interpolation_replace(self, match):
  570. s = match.group(1)
  571. if s is None:
  572. return match.group()
  573. else:
  574. return "%%(%s)s" % self.optionxform(s)
  575. class SafeConfigParser(ConfigParser):
  576. def _interpolate(self, section, option, rawval, vars):
  577. # do the string interpolation
  578. L = []
  579. self._interpolate_some(option, L, rawval, section, vars, 1)
  580. return ''.join(L)
  581. _interpvar_re = re.compile(r"%\(([^)]+)\)s")
  582. def _interpolate_some(self, option, accum, rest, section, map, depth):
  583. if depth > MAX_INTERPOLATION_DEPTH:
  584. raise InterpolationDepthError(option, section, rest)
  585. while rest:
  586. p = rest.find("%")
  587. if p < 0:
  588. accum.append(rest)
  589. return
  590. if p > 0:
  591. accum.append(rest[:p])
  592. rest = rest[p:]
  593. # p is no longer used
  594. c = rest[1:2]
  595. if c == "%":
  596. accum.append("%")
  597. rest = rest[2:]
  598. elif c == "(":
  599. m = self._interpvar_re.match(rest)
  600. if m is None:
  601. raise InterpolationSyntaxError(option, section,
  602. "bad interpolation variable reference %r" % rest)
  603. var = self.optionxform(m.group(1))
  604. rest = rest[m.end():]
  605. try:
  606. v = map[var]
  607. except KeyError:
  608. raise InterpolationMissingOptionError(
  609. option, section, rest, var)
  610. if "%" in v:
  611. self._interpolate_some(option, accum, v,
  612. section, map, depth + 1)
  613. else:
  614. accum.append(v)
  615. else:
  616. raise InterpolationSyntaxError(
  617. option, section,
  618. "'%%' must be followed by '%%' or '(', found: %r" % (rest,))
  619. def set(self, section, option, value=None):
  620. """Set an option. Extend ConfigParser.set: check for string values."""
  621. # The only legal non-string value if we allow valueless
  622. # options is None, so we need to check if the value is a
  623. # string if:
  624. # - we do not allow valueless options, or
  625. # - we allow valueless options but the value is not None
  626. if self._optcre is self.OPTCRE or value:
  627. if not isinstance(value, basestring):
  628. raise TypeError("option values must be strings")
  629. if value is not None:
  630. # check for bad percent signs:
  631. # first, replace all "good" interpolations
  632. tmp_value = value.replace('%%', '')
  633. tmp_value = self._interpvar_re.sub('', tmp_value)
  634. # then, check if there's a lone percent sign left
  635. if '%' in tmp_value:
  636. raise ValueError("invalid interpolation syntax in %r at "
  637. "position %d" % (value, tmp_value.find('%')))
  638. ConfigParser.set(self, section, option, value)