configparser.py 53 KB

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