logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

configparser.py (54630B)


  1. """Configuration file parser.
  2. A configuration 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. Intrinsic defaults can be specified by passing them into the
  6. ConfigParser constructor as a dictionary.
  7. class:
  8. ConfigParser -- responsible for parsing a list of
  9. configuration files, and managing the parsed database.
  10. methods:
  11. __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
  12. delimiters=('=', ':'), comment_prefixes=('#', ';'),
  13. inline_comment_prefixes=None, strict=True,
  14. empty_lines_in_values=True, default_section='DEFAULT',
  15. interpolation=<unset>, converters=<unset>):
  16. Create the parser. When `defaults' is given, it is initialized into the
  17. dictionary or intrinsic defaults. The keys must be strings, the values
  18. must be appropriate for %()s string interpolation.
  19. When `dict_type' is given, it will be used to create the dictionary
  20. objects for the list of sections, for the options within a section, and
  21. for the default values.
  22. When `delimiters' is given, it will be used as the set of substrings
  23. that divide keys from values.
  24. When `comment_prefixes' is given, it will be used as the set of
  25. substrings that prefix comments in empty lines. Comments can be
  26. indented.
  27. When `inline_comment_prefixes' is given, it will be used as the set of
  28. substrings that prefix comments in non-empty lines.
  29. When `strict` is True, the parser won't allow for any section or option
  30. duplicates while reading from a single source (file, string or
  31. dictionary). Default is True.
  32. When `empty_lines_in_values' is False (default: True), each empty line
  33. marks the end of an option. Otherwise, internal empty lines of
  34. a multiline option are kept as part of the value.
  35. When `allow_no_value' is True (default: False), options without
  36. values are accepted; the value presented for these is None.
  37. When `default_section' is given, the name of the special section is
  38. named accordingly. By default it is called ``"DEFAULT"`` but this can
  39. be customized to point to any other valid section name. Its current
  40. value can be retrieved using the ``parser_instance.default_section``
  41. attribute and may be modified at runtime.
  42. When `interpolation` is given, it should be an Interpolation subclass
  43. instance. It will be used as the handler for option value
  44. pre-processing when using getters. RawConfigParser objects don't do
  45. any sort of interpolation, whereas ConfigParser uses an instance of
  46. BasicInterpolation. The library also provides a ``zc.buildbot``
  47. inspired ExtendedInterpolation implementation.
  48. When `converters` is given, it should be a dictionary where each key
  49. represents the name of a type converter and each value is a callable
  50. implementing the conversion from string to the desired datatype. Every
  51. converter gets its corresponding get*() method on the parser object and
  52. section proxies.
  53. sections()
  54. Return all the configuration section names, sans DEFAULT.
  55. has_section(section)
  56. Return whether the given section exists.
  57. has_option(section, option)
  58. Return whether the given option exists in the given section.
  59. options(section)
  60. Return list of configuration options for the named section.
  61. read(filenames, encoding=None)
  62. Read and parse the iterable of named configuration files, given by
  63. name. A single filename is also allowed. Non-existing files
  64. are ignored. Return list of successfully read files.
  65. read_file(f, filename=None)
  66. Read and parse one configuration file, given as a file object.
  67. The filename defaults to f.name; it is only used in error
  68. messages (if f has no `name' attribute, the string `<???>' is used).
  69. read_string(string)
  70. Read configuration from a given string.
  71. read_dict(dictionary)
  72. Read configuration from a dictionary. Keys are section names,
  73. values are dictionaries with keys and values that should be present
  74. in the section. If the used dictionary type preserves order, sections
  75. and their keys will be added in order. Values are automatically
  76. converted to strings.
  77. get(section, option, raw=False, vars=None, fallback=_UNSET)
  78. Return a string value for the named option. All % interpolations are
  79. expanded in the return values, based on the defaults passed into the
  80. constructor and the DEFAULT section. Additional substitutions may be
  81. provided using the `vars' argument, which must be a dictionary whose
  82. contents override any pre-existing defaults. If `option' is a key in
  83. `vars', the value from `vars' is used.
  84. getint(section, options, raw=False, vars=None, fallback=_UNSET)
  85. Like get(), but convert value to an integer.
  86. getfloat(section, options, raw=False, vars=None, fallback=_UNSET)
  87. Like get(), but convert value to a float.
  88. getboolean(section, options, raw=False, vars=None, fallback=_UNSET)
  89. Like get(), but convert value to a boolean (currently case
  90. insensitively defined as 0, false, no, off for False, and 1, true,
  91. yes, on for True). Returns False or True.
  92. items(section=_UNSET, raw=False, vars=None)
  93. If section is given, return a list of tuples with (name, value) for
  94. each option in the section. Otherwise, return a list of tuples with
  95. (section_name, section_proxy) for each section, including DEFAULTSECT.
  96. remove_section(section)
  97. Remove the given file section and all its options.
  98. remove_option(section, option)
  99. Remove the given option from the given section.
  100. set(section, option, value)
  101. Set the given option.
  102. write(fp, space_around_delimiters=True)
  103. Write the configuration state in .ini format. If
  104. `space_around_delimiters' is True (the default), delimiters
  105. between keys and values are surrounded by spaces.
  106. """
  107. from collections.abc import MutableMapping
  108. from collections import ChainMap as _ChainMap
  109. import functools
  110. import io
  111. import itertools
  112. import os
  113. import re
  114. import sys
  115. import warnings
  116. __all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError",
  117. "NoOptionError", "InterpolationError", "InterpolationDepthError",
  118. "InterpolationMissingOptionError", "InterpolationSyntaxError",
  119. "ParsingError", "MissingSectionHeaderError",
  120. "ConfigParser", "SafeConfigParser", "RawConfigParser",
  121. "Interpolation", "BasicInterpolation", "ExtendedInterpolation",
  122. "LegacyInterpolation", "SectionProxy", "ConverterMapping",
  123. "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]
  124. _default_dict = dict
  125. DEFAULTSECT = "DEFAULT"
  126. MAX_INTERPOLATION_DEPTH = 10
  127. # exception classes
  128. class Error(Exception):
  129. """Base class for ConfigParser exceptions."""
  130. def __init__(self, msg=''):
  131. self.message = msg
  132. Exception.__init__(self, msg)
  133. def __repr__(self):
  134. return self.message
  135. __str__ = __repr__
  136. class NoSectionError(Error):
  137. """Raised when no section matches a requested option."""
  138. def __init__(self, section):
  139. Error.__init__(self, 'No section: %r' % (section,))
  140. self.section = section
  141. self.args = (section, )
  142. class DuplicateSectionError(Error):
  143. """Raised when a section is repeated in an input source.
  144. Possible repetitions that raise this exception are: multiple creation
  145. using the API or in strict parsers when a section is found more than once
  146. in a single input file, string or dictionary.
  147. """
  148. def __init__(self, section, source=None, lineno=None):
  149. msg = [repr(section), " already exists"]
  150. if source is not None:
  151. message = ["While reading from ", repr(source)]
  152. if lineno is not None:
  153. message.append(" [line {0:2d}]".format(lineno))
  154. message.append(": section ")
  155. message.extend(msg)
  156. msg = message
  157. else:
  158. msg.insert(0, "Section ")
  159. Error.__init__(self, "".join(msg))
  160. self.section = section
  161. self.source = source
  162. self.lineno = lineno
  163. self.args = (section, source, lineno)
  164. class DuplicateOptionError(Error):
  165. """Raised by strict parsers when an option is repeated in an input source.
  166. Current implementation raises this exception only when an option is found
  167. more than once in a single file, string or dictionary.
  168. """
  169. def __init__(self, section, option, source=None, lineno=None):
  170. msg = [repr(option), " in section ", repr(section),
  171. " already exists"]
  172. if source is not None:
  173. message = ["While reading from ", repr(source)]
  174. if lineno is not None:
  175. message.append(" [line {0:2d}]".format(lineno))
  176. message.append(": option ")
  177. message.extend(msg)
  178. msg = message
  179. else:
  180. msg.insert(0, "Option ")
  181. Error.__init__(self, "".join(msg))
  182. self.section = section
  183. self.option = option
  184. self.source = source
  185. self.lineno = lineno
  186. self.args = (section, option, source, lineno)
  187. class NoOptionError(Error):
  188. """A requested option was not found."""
  189. def __init__(self, option, section):
  190. Error.__init__(self, "No option %r in section: %r" %
  191. (option, section))
  192. self.option = option
  193. self.section = section
  194. self.args = (option, section)
  195. class InterpolationError(Error):
  196. """Base class for interpolation-related exceptions."""
  197. def __init__(self, option, section, msg):
  198. Error.__init__(self, msg)
  199. self.option = option
  200. self.section = section
  201. self.args = (option, section, msg)
  202. class InterpolationMissingOptionError(InterpolationError):
  203. """A string substitution required a setting which was not available."""
  204. def __init__(self, option, section, rawval, reference):
  205. msg = ("Bad value substitution: option {!r} in section {!r} contains "
  206. "an interpolation key {!r} which is not a valid option name. "
  207. "Raw value: {!r}".format(option, section, reference, rawval))
  208. InterpolationError.__init__(self, option, section, msg)
  209. self.reference = reference
  210. self.args = (option, section, rawval, reference)
  211. class InterpolationSyntaxError(InterpolationError):
  212. """Raised when the source text contains invalid syntax.
  213. Current implementation raises this exception when the source text into
  214. which substitutions are made does not conform to the required syntax.
  215. """
  216. class InterpolationDepthError(InterpolationError):
  217. """Raised when substitutions are nested too deeply."""
  218. def __init__(self, option, section, rawval):
  219. msg = ("Recursion limit exceeded in value substitution: option {!r} "
  220. "in section {!r} contains an interpolation key which "
  221. "cannot be substituted in {} steps. Raw value: {!r}"
  222. "".format(option, section, MAX_INTERPOLATION_DEPTH,
  223. rawval))
  224. InterpolationError.__init__(self, option, section, msg)
  225. self.args = (option, section, rawval)
  226. class ParsingError(Error):
  227. """Raised when a configuration file does not follow legal syntax."""
  228. def __init__(self, source=None, filename=None):
  229. # Exactly one of `source'/`filename' arguments has to be given.
  230. # `filename' kept for compatibility.
  231. if filename and source:
  232. raise ValueError("Cannot specify both `filename' and `source'. "
  233. "Use `source'.")
  234. elif not filename and not source:
  235. raise ValueError("Required argument `source' not given.")
  236. elif filename:
  237. source = filename
  238. Error.__init__(self, 'Source contains parsing errors: %r' % source)
  239. self.source = source
  240. self.errors = []
  241. self.args = (source, )
  242. @property
  243. def filename(self):
  244. """Deprecated, use `source'."""
  245. warnings.warn(
  246. "The 'filename' attribute will be removed in future versions. "
  247. "Use 'source' instead.",
  248. DeprecationWarning, stacklevel=2
  249. )
  250. return self.source
  251. @filename.setter
  252. def filename(self, value):
  253. """Deprecated, user `source'."""
  254. warnings.warn(
  255. "The 'filename' attribute will be removed in future versions. "
  256. "Use 'source' instead.",
  257. DeprecationWarning, stacklevel=2
  258. )
  259. self.source = value
  260. def append(self, lineno, line):
  261. self.errors.append((lineno, line))
  262. self.message += '\n\t[line %2d]: %s' % (lineno, line)
  263. class MissingSectionHeaderError(ParsingError):
  264. """Raised when a key-value pair is found before any section header."""
  265. def __init__(self, filename, lineno, line):
  266. Error.__init__(
  267. self,
  268. 'File contains no section headers.\nfile: %r, line: %d\n%r' %
  269. (filename, lineno, line))
  270. self.source = filename
  271. self.lineno = lineno
  272. self.line = line
  273. self.args = (filename, lineno, line)
  274. # Used in parser getters to indicate the default behaviour when a specific
  275. # option is not found it to raise an exception. Created to enable `None' as
  276. # a valid fallback value.
  277. _UNSET = object()
  278. class Interpolation:
  279. """Dummy interpolation that passes the value through with no changes."""
  280. def before_get(self, parser, section, option, value, defaults):
  281. return value
  282. def before_set(self, parser, section, option, value):
  283. return value
  284. def before_read(self, parser, section, option, value):
  285. return value
  286. def before_write(self, parser, section, option, value):
  287. return value
  288. class BasicInterpolation(Interpolation):
  289. """Interpolation as implemented in the classic ConfigParser.
  290. The option values can contain format strings which refer to other values in
  291. the same section, or values in the special default section.
  292. For example:
  293. something: %(dir)s/whatever
  294. would resolve the "%(dir)s" to the value of dir. All reference
  295. expansions are done late, on demand. If a user needs to use a bare % in
  296. a configuration file, she can escape it by writing %%. Other % usage
  297. is considered a user error and raises `InterpolationSyntaxError'."""
  298. _KEYCRE = re.compile(r"%\(([^)]+)\)s")
  299. def before_get(self, parser, section, option, value, defaults):
  300. L = []
  301. self._interpolate_some(parser, option, L, value, section, defaults, 1)
  302. return ''.join(L)
  303. def before_set(self, parser, section, option, value):
  304. tmp_value = value.replace('%%', '') # escaped percent signs
  305. tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
  306. if '%' in tmp_value:
  307. raise ValueError("invalid interpolation syntax in %r at "
  308. "position %d" % (value, tmp_value.find('%')))
  309. return value
  310. def _interpolate_some(self, parser, option, accum, rest, section, map,
  311. depth):
  312. rawval = parser.get(section, option, raw=True, fallback=rest)
  313. if depth > MAX_INTERPOLATION_DEPTH:
  314. raise InterpolationDepthError(option, section, rawval)
  315. while rest:
  316. p = rest.find("%")
  317. if p < 0:
  318. accum.append(rest)
  319. return
  320. if p > 0:
  321. accum.append(rest[:p])
  322. rest = rest[p:]
  323. # p is no longer used
  324. c = rest[1:2]
  325. if c == "%":
  326. accum.append("%")
  327. rest = rest[2:]
  328. elif c == "(":
  329. m = self._KEYCRE.match(rest)
  330. if m is None:
  331. raise InterpolationSyntaxError(option, section,
  332. "bad interpolation variable reference %r" % rest)
  333. var = parser.optionxform(m.group(1))
  334. rest = rest[m.end():]
  335. try:
  336. v = map[var]
  337. except KeyError:
  338. raise InterpolationMissingOptionError(
  339. option, section, rawval, var) from None
  340. if "%" in v:
  341. self._interpolate_some(parser, option, accum, v,
  342. section, map, depth + 1)
  343. else:
  344. accum.append(v)
  345. else:
  346. raise InterpolationSyntaxError(
  347. option, section,
  348. "'%%' must be followed by '%%' or '(', "
  349. "found: %r" % (rest,))
  350. class ExtendedInterpolation(Interpolation):
  351. """Advanced variant of interpolation, supports the syntax used by
  352. `zc.buildout'. Enables interpolation between sections."""
  353. _KEYCRE = re.compile(r"\$\{([^}]+)\}")
  354. def before_get(self, parser, section, option, value, defaults):
  355. L = []
  356. self._interpolate_some(parser, option, L, value, section, defaults, 1)
  357. return ''.join(L)
  358. def before_set(self, parser, section, option, value):
  359. tmp_value = value.replace('$$', '') # escaped dollar signs
  360. tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
  361. if '$' in tmp_value:
  362. raise ValueError("invalid interpolation syntax in %r at "
  363. "position %d" % (value, tmp_value.find('$')))
  364. return value
  365. def _interpolate_some(self, parser, option, accum, rest, section, map,
  366. depth):
  367. rawval = parser.get(section, option, raw=True, fallback=rest)
  368. if depth > MAX_INTERPOLATION_DEPTH:
  369. raise InterpolationDepthError(option, section, rawval)
  370. while rest:
  371. p = rest.find("$")
  372. if p < 0:
  373. accum.append(rest)
  374. return
  375. if p > 0:
  376. accum.append(rest[:p])
  377. rest = rest[p:]
  378. # p is no longer used
  379. c = rest[1:2]
  380. if c == "$":
  381. accum.append("$")
  382. rest = rest[2:]
  383. elif c == "{":
  384. m = self._KEYCRE.match(rest)
  385. if m is None:
  386. raise InterpolationSyntaxError(option, section,
  387. "bad interpolation variable reference %r" % rest)
  388. path = m.group(1).split(':')
  389. rest = rest[m.end():]
  390. sect = section
  391. opt = option
  392. try:
  393. if len(path) == 1:
  394. opt = parser.optionxform(path[0])
  395. v = map[opt]
  396. elif len(path) == 2:
  397. sect = path[0]
  398. opt = parser.optionxform(path[1])
  399. v = parser.get(sect, opt, raw=True)
  400. else:
  401. raise InterpolationSyntaxError(
  402. option, section,
  403. "More than one ':' found: %r" % (rest,))
  404. except (KeyError, NoSectionError, NoOptionError):
  405. raise InterpolationMissingOptionError(
  406. option, section, rawval, ":".join(path)) from None
  407. if "$" in v:
  408. self._interpolate_some(parser, opt, accum, v, sect,
  409. dict(parser.items(sect, raw=True)),
  410. depth + 1)
  411. else:
  412. accum.append(v)
  413. else:
  414. raise InterpolationSyntaxError(
  415. option, section,
  416. "'$' must be followed by '$' or '{', "
  417. "found: %r" % (rest,))
  418. class LegacyInterpolation(Interpolation):
  419. """Deprecated interpolation used in old versions of ConfigParser.
  420. Use BasicInterpolation or ExtendedInterpolation instead."""
  421. _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
  422. def before_get(self, parser, section, option, value, vars):
  423. rawval = value
  424. depth = MAX_INTERPOLATION_DEPTH
  425. while depth: # Loop through this until it's done
  426. depth -= 1
  427. if value and "%(" in value:
  428. replace = functools.partial(self._interpolation_replace,
  429. parser=parser)
  430. value = self._KEYCRE.sub(replace, value)
  431. try:
  432. value = value % vars
  433. except KeyError as e:
  434. raise InterpolationMissingOptionError(
  435. option, section, rawval, e.args[0]) from None
  436. else:
  437. break
  438. if value and "%(" in value:
  439. raise InterpolationDepthError(option, section, rawval)
  440. return value
  441. def before_set(self, parser, section, option, value):
  442. return value
  443. @staticmethod
  444. def _interpolation_replace(match, parser):
  445. s = match.group(1)
  446. if s is None:
  447. return match.group()
  448. else:
  449. return "%%(%s)s" % parser.optionxform(s)
  450. class RawConfigParser(MutableMapping):
  451. """ConfigParser that does not do interpolation."""
  452. # Regular expressions for parsing section headers and options
  453. _SECT_TMPL = r"""
  454. \[ # [
  455. (?P<header>.+) # very permissive!
  456. \] # ]
  457. """
  458. _OPT_TMPL = r"""
  459. (?P<option>.*?) # very permissive!
  460. \s*(?P<vi>{delim})\s* # any number of space/tab,
  461. # followed by any of the
  462. # allowed delimiters,
  463. # followed by any space/tab
  464. (?P<value>.*)$ # everything up to eol
  465. """
  466. _OPT_NV_TMPL = r"""
  467. (?P<option>.*?) # very permissive!
  468. \s*(?: # any number of space/tab,
  469. (?P<vi>{delim})\s* # optionally followed by
  470. # any of the allowed
  471. # delimiters, followed by any
  472. # space/tab
  473. (?P<value>.*))?$ # everything up to eol
  474. """
  475. # Interpolation algorithm to be used if the user does not specify another
  476. _DEFAULT_INTERPOLATION = Interpolation()
  477. # Compiled regular expression for matching sections
  478. SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
  479. # Compiled regular expression for matching options with typical separators
  480. OPTCRE = re.compile(_OPT_TMPL.format(delim="=|:"), re.VERBOSE)
  481. # Compiled regular expression for matching options with optional values
  482. # delimited using typical separators
  483. OPTCRE_NV = re.compile(_OPT_NV_TMPL.format(delim="=|:"), re.VERBOSE)
  484. # Compiled regular expression for matching leading whitespace in a line
  485. NONSPACECRE = re.compile(r"\S")
  486. # Possible boolean values in the configuration.
  487. BOOLEAN_STATES = {'1': True, 'yes': True, 'true': True, 'on': True,
  488. '0': False, 'no': False, 'false': False, 'off': False}
  489. def __init__(self, defaults=None, dict_type=_default_dict,
  490. allow_no_value=False, *, delimiters=('=', ':'),
  491. comment_prefixes=('#', ';'), inline_comment_prefixes=None,
  492. strict=True, empty_lines_in_values=True,
  493. default_section=DEFAULTSECT,
  494. interpolation=_UNSET, converters=_UNSET):
  495. self._dict = dict_type
  496. self._sections = self._dict()
  497. self._defaults = self._dict()
  498. self._converters = ConverterMapping(self)
  499. self._proxies = self._dict()
  500. self._proxies[default_section] = SectionProxy(self, default_section)
  501. self._delimiters = tuple(delimiters)
  502. if delimiters == ('=', ':'):
  503. self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE
  504. else:
  505. d = "|".join(re.escape(d) for d in delimiters)
  506. if allow_no_value:
  507. self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d),
  508. re.VERBOSE)
  509. else:
  510. self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
  511. re.VERBOSE)
  512. self._comment_prefixes = tuple(comment_prefixes or ())
  513. self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
  514. self._strict = strict
  515. self._allow_no_value = allow_no_value
  516. self._empty_lines_in_values = empty_lines_in_values
  517. self.default_section=default_section
  518. self._interpolation = interpolation
  519. if self._interpolation is _UNSET:
  520. self._interpolation = self._DEFAULT_INTERPOLATION
  521. if self._interpolation is None:
  522. self._interpolation = Interpolation()
  523. if converters is not _UNSET:
  524. self._converters.update(converters)
  525. if defaults:
  526. self._read_defaults(defaults)
  527. def defaults(self):
  528. return self._defaults
  529. def sections(self):
  530. """Return a list of section names, excluding [DEFAULT]"""
  531. # self._sections will never have [DEFAULT] in it
  532. return list(self._sections.keys())
  533. def add_section(self, section):
  534. """Create a new section in the configuration.
  535. Raise DuplicateSectionError if a section by the specified name
  536. already exists. Raise ValueError if name is DEFAULT.
  537. """
  538. if section == self.default_section:
  539. raise ValueError('Invalid section name: %r' % section)
  540. if section in self._sections:
  541. raise DuplicateSectionError(section)
  542. self._sections[section] = self._dict()
  543. self._proxies[section] = SectionProxy(self, section)
  544. def has_section(self, section):
  545. """Indicate whether the named section is present in the configuration.
  546. The DEFAULT section is not acknowledged.
  547. """
  548. return section in self._sections
  549. def options(self, section):
  550. """Return a list of option names for the given section name."""
  551. try:
  552. opts = self._sections[section].copy()
  553. except KeyError:
  554. raise NoSectionError(section) from None
  555. opts.update(self._defaults)
  556. return list(opts.keys())
  557. def read(self, filenames, encoding=None):
  558. """Read and parse a filename or an iterable of filenames.
  559. Files that cannot be opened are silently ignored; this is
  560. designed so that you can specify an iterable of potential
  561. configuration file locations (e.g. current directory, user's
  562. home directory, systemwide directory), and all existing
  563. configuration files in the iterable will be read. A single
  564. filename may also be given.
  565. Return list of successfully read files.
  566. """
  567. if isinstance(filenames, (str, bytes, os.PathLike)):
  568. filenames = [filenames]
  569. encoding = io.text_encoding(encoding)
  570. read_ok = []
  571. for filename in filenames:
  572. try:
  573. with open(filename, encoding=encoding) as fp:
  574. self._read(fp, filename)
  575. except OSError:
  576. continue
  577. if isinstance(filename, os.PathLike):
  578. filename = os.fspath(filename)
  579. read_ok.append(filename)
  580. return read_ok
  581. def read_file(self, f, source=None):
  582. """Like read() but the argument must be a file-like object.
  583. The `f' argument must be iterable, returning one line at a time.
  584. Optional second argument is the `source' specifying the name of the
  585. file being read. If not given, it is taken from f.name. If `f' has no
  586. `name' attribute, `<???>' is used.
  587. """
  588. if source is None:
  589. try:
  590. source = f.name
  591. except AttributeError:
  592. source = '<???>'
  593. self._read(f, source)
  594. def read_string(self, string, source='<string>'):
  595. """Read configuration from a given string."""
  596. sfile = io.StringIO(string)
  597. self.read_file(sfile, source)
  598. def read_dict(self, dictionary, source='<dict>'):
  599. """Read configuration from a dictionary.
  600. Keys are section names, values are dictionaries with keys and values
  601. that should be present in the section. If the used dictionary type
  602. preserves order, sections and their keys will be added in order.
  603. All types held in the dictionary are converted to strings during
  604. reading, including section names, option names and keys.
  605. Optional second argument is the `source' specifying the name of the
  606. dictionary being read.
  607. """
  608. elements_added = set()
  609. for section, keys in dictionary.items():
  610. section = str(section)
  611. try:
  612. self.add_section(section)
  613. except (DuplicateSectionError, ValueError):
  614. if self._strict and section in elements_added:
  615. raise
  616. elements_added.add(section)
  617. for key, value in keys.items():
  618. key = self.optionxform(str(key))
  619. if value is not None:
  620. value = str(value)
  621. if self._strict and (section, key) in elements_added:
  622. raise DuplicateOptionError(section, key, source)
  623. elements_added.add((section, key))
  624. self.set(section, key, value)
  625. def readfp(self, fp, filename=None):
  626. """Deprecated, use read_file instead."""
  627. warnings.warn(
  628. "This method will be removed in future versions. "
  629. "Use 'parser.read_file()' instead.",
  630. DeprecationWarning, stacklevel=2
  631. )
  632. self.read_file(fp, source=filename)
  633. def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
  634. """Get an option value for a given section.
  635. If `vars' is provided, it must be a dictionary. The option is looked up
  636. in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
  637. If the key is not found and `fallback' is provided, it is used as
  638. a fallback value. `None' can be provided as a `fallback' value.
  639. If interpolation is enabled and the optional argument `raw' is False,
  640. all interpolations are expanded in the return values.
  641. Arguments `raw', `vars', and `fallback' are keyword only.
  642. The section DEFAULT is special.
  643. """
  644. try:
  645. d = self._unify_values(section, vars)
  646. except NoSectionError:
  647. if fallback is _UNSET:
  648. raise
  649. else:
  650. return fallback
  651. option = self.optionxform(option)
  652. try:
  653. value = d[option]
  654. except KeyError:
  655. if fallback is _UNSET:
  656. raise NoOptionError(option, section)
  657. else:
  658. return fallback
  659. if raw or value is None:
  660. return value
  661. else:
  662. return self._interpolation.before_get(self, section, option, value,
  663. d)
  664. def _get(self, section, conv, option, **kwargs):
  665. return conv(self.get(section, option, **kwargs))
  666. def _get_conv(self, section, option, conv, *, raw=False, vars=None,
  667. fallback=_UNSET, **kwargs):
  668. try:
  669. return self._get(section, conv, option, raw=raw, vars=vars,
  670. **kwargs)
  671. except (NoSectionError, NoOptionError):
  672. if fallback is _UNSET:
  673. raise
  674. return fallback
  675. # getint, getfloat and getboolean provided directly for backwards compat
  676. def getint(self, section, option, *, raw=False, vars=None,
  677. fallback=_UNSET, **kwargs):
  678. return self._get_conv(section, option, int, raw=raw, vars=vars,
  679. fallback=fallback, **kwargs)
  680. def getfloat(self, section, option, *, raw=False, vars=None,
  681. fallback=_UNSET, **kwargs):
  682. return self._get_conv(section, option, float, raw=raw, vars=vars,
  683. fallback=fallback, **kwargs)
  684. def getboolean(self, section, option, *, raw=False, vars=None,
  685. fallback=_UNSET, **kwargs):
  686. return self._get_conv(section, option, self._convert_to_boolean,
  687. raw=raw, vars=vars, fallback=fallback, **kwargs)
  688. def items(self, section=_UNSET, raw=False, vars=None):
  689. """Return a list of (name, value) tuples for each option in a section.
  690. All % interpolations are expanded in the return values, based on the
  691. defaults passed into the constructor, unless the optional argument
  692. `raw' is true. Additional substitutions may be provided using the
  693. `vars' argument, which must be a dictionary whose contents overrides
  694. any pre-existing defaults.
  695. The section DEFAULT is special.
  696. """
  697. if section is _UNSET:
  698. return super().items()
  699. d = self._defaults.copy()
  700. try:
  701. d.update(self._sections[section])
  702. except KeyError:
  703. if section != self.default_section:
  704. raise NoSectionError(section)
  705. orig_keys = list(d.keys())
  706. # Update with the entry specific variables
  707. if vars:
  708. for key, value in vars.items():
  709. d[self.optionxform(key)] = value
  710. value_getter = lambda option: self._interpolation.before_get(self,
  711. section, option, d[option], d)
  712. if raw:
  713. value_getter = lambda option: d[option]
  714. return [(option, value_getter(option)) for option in orig_keys]
  715. def popitem(self):
  716. """Remove a section from the parser and return it as
  717. a (section_name, section_proxy) tuple. If no section is present, raise
  718. KeyError.
  719. The section DEFAULT is never returned because it cannot be removed.
  720. """
  721. for key in self.sections():
  722. value = self[key]
  723. del self[key]
  724. return key, value
  725. raise KeyError
  726. def optionxform(self, optionstr):
  727. return optionstr.lower()
  728. def has_option(self, section, option):
  729. """Check for the existence of a given option in a given section.
  730. If the specified `section' is None or an empty string, DEFAULT is
  731. assumed. If the specified `section' does not exist, returns False."""
  732. if not section or section == self.default_section:
  733. option = self.optionxform(option)
  734. return option in self._defaults
  735. elif section not in self._sections:
  736. return False
  737. else:
  738. option = self.optionxform(option)
  739. return (option in self._sections[section]
  740. or option in self._defaults)
  741. def set(self, section, option, value=None):
  742. """Set an option."""
  743. if value:
  744. value = self._interpolation.before_set(self, section, option,
  745. value)
  746. if not section or section == self.default_section:
  747. sectdict = self._defaults
  748. else:
  749. try:
  750. sectdict = self._sections[section]
  751. except KeyError:
  752. raise NoSectionError(section) from None
  753. sectdict[self.optionxform(option)] = value
  754. def write(self, fp, space_around_delimiters=True):
  755. """Write an .ini-format representation of the configuration state.
  756. If `space_around_delimiters' is True (the default), delimiters
  757. between keys and values are surrounded by spaces.
  758. Please note that comments in the original configuration file are not
  759. preserved when writing the configuration back.
  760. """
  761. if space_around_delimiters:
  762. d = " {} ".format(self._delimiters[0])
  763. else:
  764. d = self._delimiters[0]
  765. if self._defaults:
  766. self._write_section(fp, self.default_section,
  767. self._defaults.items(), d)
  768. for section in self._sections:
  769. self._write_section(fp, section,
  770. self._sections[section].items(), d)
  771. def _write_section(self, fp, section_name, section_items, delimiter):
  772. """Write a single section to the specified `fp'."""
  773. fp.write("[{}]\n".format(section_name))
  774. for key, value in section_items:
  775. value = self._interpolation.before_write(self, section_name, key,
  776. value)
  777. if value is not None or not self._allow_no_value:
  778. value = delimiter + str(value).replace('\n', '\n\t')
  779. else:
  780. value = ""
  781. fp.write("{}{}\n".format(key, value))
  782. fp.write("\n")
  783. def remove_option(self, section, option):
  784. """Remove an option."""
  785. if not section or section == self.default_section:
  786. sectdict = self._defaults
  787. else:
  788. try:
  789. sectdict = self._sections[section]
  790. except KeyError:
  791. raise NoSectionError(section) from None
  792. option = self.optionxform(option)
  793. existed = option in sectdict
  794. if existed:
  795. del sectdict[option]
  796. return existed
  797. def remove_section(self, section):
  798. """Remove a file section."""
  799. existed = section in self._sections
  800. if existed:
  801. del self._sections[section]
  802. del self._proxies[section]
  803. return existed
  804. def __getitem__(self, key):
  805. if key != self.default_section and not self.has_section(key):
  806. raise KeyError(key)
  807. return self._proxies[key]
  808. def __setitem__(self, key, value):
  809. # To conform with the mapping protocol, overwrites existing values in
  810. # the section.
  811. if key in self and self[key] is value:
  812. return
  813. # XXX this is not atomic if read_dict fails at any point. Then again,
  814. # no update method in configparser is atomic in this implementation.
  815. if key == self.default_section:
  816. self._defaults.clear()
  817. elif key in self._sections:
  818. self._sections[key].clear()
  819. self.read_dict({key: value})
  820. def __delitem__(self, key):
  821. if key == self.default_section:
  822. raise ValueError("Cannot remove the default section.")
  823. if not self.has_section(key):
  824. raise KeyError(key)
  825. self.remove_section(key)
  826. def __contains__(self, key):
  827. return key == self.default_section or self.has_section(key)
  828. def __len__(self):
  829. return len(self._sections) + 1 # the default section
  830. def __iter__(self):
  831. # XXX does it break when underlying container state changed?
  832. return itertools.chain((self.default_section,), self._sections.keys())
  833. def _read(self, fp, fpname):
  834. """Parse a sectioned configuration file.
  835. Each section in a configuration file contains a header, indicated by
  836. a name in square brackets (`[]'), plus key/value options, indicated by
  837. `name' and `value' delimited with a specific substring (`=' or `:' by
  838. default).
  839. Values can span multiple lines, as long as they are indented deeper
  840. than the first line of the value. Depending on the parser's mode, blank
  841. lines may be treated as parts of multiline values or ignored.
  842. Configuration files may include comments, prefixed by specific
  843. characters (`#' and `;' by default). Comments may appear on their own
  844. in an otherwise empty line or may be entered in lines holding values or
  845. section names. Please note that comments get stripped off when reading configuration files.
  846. """
  847. elements_added = set()
  848. cursect = None # None, or a dictionary
  849. sectname = None
  850. optname = None
  851. lineno = 0
  852. indent_level = 0
  853. e = None # None, or an exception
  854. for lineno, line in enumerate(fp, start=1):
  855. comment_start = sys.maxsize
  856. # strip inline comments
  857. inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
  858. while comment_start == sys.maxsize and inline_prefixes:
  859. next_prefixes = {}
  860. for prefix, index in inline_prefixes.items():
  861. index = line.find(prefix, index+1)
  862. if index == -1:
  863. continue
  864. next_prefixes[prefix] = index
  865. if index == 0 or (index > 0 and line[index-1].isspace()):
  866. comment_start = min(comment_start, index)
  867. inline_prefixes = next_prefixes
  868. # strip full line comments
  869. for prefix in self._comment_prefixes:
  870. if line.strip().startswith(prefix):
  871. comment_start = 0
  872. break
  873. if comment_start == sys.maxsize:
  874. comment_start = None
  875. value = line[:comment_start].strip()
  876. if not value:
  877. if self._empty_lines_in_values:
  878. # add empty line to the value, but only if there was no
  879. # comment on the line
  880. if (comment_start is None and
  881. cursect is not None and
  882. optname and
  883. cursect[optname] is not None):
  884. cursect[optname].append('') # newlines added at join
  885. else:
  886. # empty line marks end of value
  887. indent_level = sys.maxsize
  888. continue
  889. # continuation line?
  890. first_nonspace = self.NONSPACECRE.search(line)
  891. cur_indent_level = first_nonspace.start() if first_nonspace else 0
  892. if (cursect is not None and optname and
  893. cur_indent_level > indent_level):
  894. cursect[optname].append(value)
  895. # a section header or option header?
  896. else:
  897. indent_level = cur_indent_level
  898. # is it a section header?
  899. mo = self.SECTCRE.match(value)
  900. if mo:
  901. sectname = mo.group('header')
  902. if sectname in self._sections:
  903. if self._strict and sectname in elements_added:
  904. raise DuplicateSectionError(sectname, fpname,
  905. lineno)
  906. cursect = self._sections[sectname]
  907. elements_added.add(sectname)
  908. elif sectname == self.default_section:
  909. cursect = self._defaults
  910. else:
  911. cursect = self._dict()
  912. self._sections[sectname] = cursect
  913. self._proxies[sectname] = SectionProxy(self, sectname)
  914. elements_added.add(sectname)
  915. # So sections can't start with a continuation line
  916. optname = None
  917. # no section header in the file?
  918. elif cursect is None:
  919. raise MissingSectionHeaderError(fpname, lineno, line)
  920. # an option line?
  921. else:
  922. mo = self._optcre.match(value)
  923. if mo:
  924. optname, vi, optval = mo.group('option', 'vi', 'value')
  925. if not optname:
  926. e = self._handle_error(e, fpname, lineno, line)
  927. optname = self.optionxform(optname.rstrip())
  928. if (self._strict and
  929. (sectname, optname) in elements_added):
  930. raise DuplicateOptionError(sectname, optname,
  931. fpname, lineno)
  932. elements_added.add((sectname, optname))
  933. # This check is fine because the OPTCRE cannot
  934. # match if it would set optval to None
  935. if optval is not None:
  936. optval = optval.strip()
  937. cursect[optname] = [optval]
  938. else:
  939. # valueless option handling
  940. cursect[optname] = None
  941. else:
  942. # a non-fatal parsing error occurred. set up the
  943. # exception but keep going. the exception will be
  944. # raised at the end of the file and will contain a
  945. # list of all bogus lines
  946. e = self._handle_error(e, fpname, lineno, line)
  947. self._join_multiline_values()
  948. # if any parsing errors occurred, raise an exception
  949. if e:
  950. raise e
  951. def _join_multiline_values(self):
  952. defaults = self.default_section, self._defaults
  953. all_sections = itertools.chain((defaults,),
  954. self._sections.items())
  955. for section, options in all_sections:
  956. for name, val in options.items():
  957. if isinstance(val, list):
  958. val = '\n'.join(val).rstrip()
  959. options[name] = self._interpolation.before_read(self,
  960. section,
  961. name, val)
  962. def _read_defaults(self, defaults):
  963. """Read the defaults passed in the initializer.
  964. Note: values can be non-string."""
  965. for key, value in defaults.items():
  966. self._defaults[self.optionxform(key)] = value
  967. def _handle_error(self, exc, fpname, lineno, line):
  968. if not exc:
  969. exc = ParsingError(fpname)
  970. exc.append(lineno, repr(line))
  971. return exc
  972. def _unify_values(self, section, vars):
  973. """Create a sequence of lookups with 'vars' taking priority over
  974. the 'section' which takes priority over the DEFAULTSECT.
  975. """
  976. sectiondict = {}
  977. try:
  978. sectiondict = self._sections[section]
  979. except KeyError:
  980. if section != self.default_section:
  981. raise NoSectionError(section) from None
  982. # Update with the entry specific variables
  983. vardict = {}
  984. if vars:
  985. for key, value in vars.items():
  986. if value is not None:
  987. value = str(value)
  988. vardict[self.optionxform(key)] = value
  989. return _ChainMap(vardict, sectiondict, self._defaults)
  990. def _convert_to_boolean(self, value):
  991. """Return a boolean value translating from other types if necessary.
  992. """
  993. if value.lower() not in self.BOOLEAN_STATES:
  994. raise ValueError('Not a boolean: %s' % value)
  995. return self.BOOLEAN_STATES[value.lower()]
  996. def _validate_value_types(self, *, section="", option="", value=""):
  997. """Raises a TypeError for non-string values.
  998. The only legal non-string value if we allow valueless
  999. options is None, so we need to check if the value is a
  1000. string if:
  1001. - we do not allow valueless options, or
  1002. - we allow valueless options but the value is not None
  1003. For compatibility reasons this method is not used in classic set()
  1004. for RawConfigParsers. It is invoked in every case for mapping protocol
  1005. access and in ConfigParser.set().
  1006. """
  1007. if not isinstance(section, str):
  1008. raise TypeError("section names must be strings")
  1009. if not isinstance(option, str):
  1010. raise TypeError("option keys must be strings")
  1011. if not self._allow_no_value or value:
  1012. if not isinstance(value, str):
  1013. raise TypeError("option values must be strings")
  1014. @property
  1015. def converters(self):
  1016. return self._converters
  1017. class ConfigParser(RawConfigParser):
  1018. """ConfigParser implementing interpolation."""
  1019. _DEFAULT_INTERPOLATION = BasicInterpolation()
  1020. def set(self, section, option, value=None):
  1021. """Set an option. Extends RawConfigParser.set by validating type and
  1022. interpolation syntax on the value."""
  1023. self._validate_value_types(option=option, value=value)
  1024. super().set(section, option, value)
  1025. def add_section(self, section):
  1026. """Create a new section in the configuration. Extends
  1027. RawConfigParser.add_section by validating if the section name is
  1028. a string."""
  1029. self._validate_value_types(section=section)
  1030. super().add_section(section)
  1031. def _read_defaults(self, defaults):
  1032. """Reads the defaults passed in the initializer, implicitly converting
  1033. values to strings like the rest of the API.
  1034. Does not perform interpolation for backwards compatibility.
  1035. """
  1036. try:
  1037. hold_interpolation = self._interpolation
  1038. self._interpolation = Interpolation()
  1039. self.read_dict({self.default_section: defaults})
  1040. finally:
  1041. self._interpolation = hold_interpolation
  1042. class SafeConfigParser(ConfigParser):
  1043. """ConfigParser alias for backwards compatibility purposes."""
  1044. def __init__(self, *args, **kwargs):
  1045. super().__init__(*args, **kwargs)
  1046. warnings.warn(
  1047. "The SafeConfigParser class has been renamed to ConfigParser "
  1048. "in Python 3.2. This alias will be removed in future versions."
  1049. " Use ConfigParser directly instead.",
  1050. DeprecationWarning, stacklevel=2
  1051. )
  1052. class SectionProxy(MutableMapping):
  1053. """A proxy for a single section from a parser."""
  1054. def __init__(self, parser, name):
  1055. """Creates a view on a section of the specified `name` in `parser`."""
  1056. self._parser = parser
  1057. self._name = name
  1058. for conv in parser.converters:
  1059. key = 'get' + conv
  1060. getter = functools.partial(self.get, _impl=getattr(parser, key))
  1061. setattr(self, key, getter)
  1062. def __repr__(self):
  1063. return '<Section: {}>'.format(self._name)
  1064. def __getitem__(self, key):
  1065. if not self._parser.has_option(self._name, key):
  1066. raise KeyError(key)
  1067. return self._parser.get(self._name, key)
  1068. def __setitem__(self, key, value):
  1069. self._parser._validate_value_types(option=key, value=value)
  1070. return self._parser.set(self._name, key, value)
  1071. def __delitem__(self, key):
  1072. if not (self._parser.has_option(self._name, key) and
  1073. self._parser.remove_option(self._name, key)):
  1074. raise KeyError(key)
  1075. def __contains__(self, key):
  1076. return self._parser.has_option(self._name, key)
  1077. def __len__(self):
  1078. return len(self._options())
  1079. def __iter__(self):
  1080. return self._options().__iter__()
  1081. def _options(self):
  1082. if self._name != self._parser.default_section:
  1083. return self._parser.options(self._name)
  1084. else:
  1085. return self._parser.defaults()
  1086. @property
  1087. def parser(self):
  1088. # The parser object of the proxy is read-only.
  1089. return self._parser
  1090. @property
  1091. def name(self):
  1092. # The name of the section on a proxy is read-only.
  1093. return self._name
  1094. def get(self, option, fallback=None, *, raw=False, vars=None,
  1095. _impl=None, **kwargs):
  1096. """Get an option value.
  1097. Unless `fallback` is provided, `None` will be returned if the option
  1098. is not found.
  1099. """
  1100. # If `_impl` is provided, it should be a getter method on the parser
  1101. # object that provides the desired type conversion.
  1102. if not _impl:
  1103. _impl = self._parser.get
  1104. return _impl(self._name, option, raw=raw, vars=vars,
  1105. fallback=fallback, **kwargs)
  1106. class ConverterMapping(MutableMapping):
  1107. """Enables reuse of get*() methods between the parser and section proxies.
  1108. If a parser class implements a getter directly, the value for the given
  1109. key will be ``None``. The presence of the converter name here enables
  1110. section proxies to find and use the implementation on the parser class.
  1111. """
  1112. GETTERCRE = re.compile(r"^get(?P<name>.+)$")
  1113. def __init__(self, parser):
  1114. self._parser = parser
  1115. self._data = {}
  1116. for getter in dir(self._parser):
  1117. m = self.GETTERCRE.match(getter)
  1118. if not m or not callable(getattr(self._parser, getter)):
  1119. continue
  1120. self._data[m.group('name')] = None # See class docstring.
  1121. def __getitem__(self, key):
  1122. return self._data[key]
  1123. def __setitem__(self, key, value):
  1124. try:
  1125. k = 'get' + key
  1126. except TypeError:
  1127. raise ValueError('Incompatible key: {} (type: {})'
  1128. ''.format(key, type(key)))
  1129. if k == 'get':
  1130. raise ValueError('Incompatible key: cannot use "" as a name')
  1131. self._data[key] = value
  1132. func = functools.partial(self._parser._get_conv, conv=value)
  1133. func.converter = value
  1134. setattr(self._parser, k, func)
  1135. for proxy in self._parser.values():
  1136. getter = functools.partial(proxy.get, _impl=func)
  1137. setattr(proxy, k, getter)
  1138. def __delitem__(self, key):
  1139. try:
  1140. k = 'get' + (key or None)
  1141. except TypeError:
  1142. raise KeyError(key)
  1143. del self._data[key]
  1144. for inst in itertools.chain((self._parser,), self._parser.values()):
  1145. try:
  1146. delattr(inst, k)
  1147. except AttributeError:
  1148. # don't raise since the entry was present in _data, silently
  1149. # clean up
  1150. continue
  1151. def __iter__(self):
  1152. return iter(self._data)
  1153. def __len__(self):
  1154. return len(self._data)