configparser.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  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. for lineno, line in enumerate(fp, start=1):
  833. comment_start = sys.maxsize
  834. # strip inline comments
  835. inline_prefixes = {p: -1 for p in self._inline_comment_prefixes}
  836. while comment_start == sys.maxsize and inline_prefixes:
  837. next_prefixes = {}
  838. for prefix, index in inline_prefixes.items():
  839. index = line.find(prefix, index+1)
  840. if index == -1:
  841. continue
  842. next_prefixes[prefix] = index
  843. if index == 0 or (index > 0 and line[index-1].isspace()):
  844. comment_start = min(comment_start, index)
  845. inline_prefixes = next_prefixes
  846. # strip full line comments
  847. for prefix in self._comment_prefixes:
  848. if line.strip().startswith(prefix):
  849. comment_start = 0
  850. break
  851. if comment_start == sys.maxsize:
  852. comment_start = None
  853. value = line[:comment_start].strip()
  854. if not value:
  855. if self._empty_lines_in_values:
  856. # add empty line to the value, but only if there was no
  857. # comment on the line
  858. if (comment_start is None and
  859. cursect is not None and
  860. optname and
  861. cursect[optname] is not None):
  862. cursect[optname].append('') # newlines added at join
  863. else:
  864. # empty line marks end of value
  865. indent_level = sys.maxsize
  866. continue
  867. # continuation line?
  868. first_nonspace = self.NONSPACECRE.search(line)
  869. cur_indent_level = first_nonspace.start() if first_nonspace else 0
  870. if (cursect is not None and optname and
  871. cur_indent_level > indent_level):
  872. cursect[optname].append(value)
  873. # a section header or option header?
  874. else:
  875. indent_level = cur_indent_level
  876. # is it a section header?
  877. mo = self.SECTCRE.match(value)
  878. if mo:
  879. sectname = mo.group('header')
  880. if sectname in self._sections:
  881. if self._strict and sectname in elements_added:
  882. raise DuplicateSectionError(sectname, fpname,
  883. lineno)
  884. cursect = self._sections[sectname]
  885. elements_added.add(sectname)
  886. elif sectname == self.default_section:
  887. cursect = self._defaults
  888. else:
  889. cursect = self._dict()
  890. self._sections[sectname] = cursect
  891. self._proxies[sectname] = SectionProxy(self, sectname)
  892. elements_added.add(sectname)
  893. # So sections can't start with a continuation line
  894. optname = None
  895. # no section header in the file?
  896. elif cursect is None:
  897. raise MissingSectionHeaderError(fpname, lineno, line)
  898. # an option line?
  899. else:
  900. mo = self._optcre.match(value)
  901. if mo:
  902. optname, vi, optval = mo.group('option', 'vi', 'value')
  903. if not optname:
  904. e = self._handle_error(e, fpname, lineno, line)
  905. optname = self.optionxform(optname.rstrip())
  906. if (self._strict and
  907. (sectname, optname) in elements_added):
  908. raise DuplicateOptionError(sectname, optname,
  909. fpname, lineno)
  910. elements_added.add((sectname, optname))
  911. # This check is fine because the OPTCRE cannot
  912. # match if it would set optval to None
  913. if optval is not None:
  914. optval = optval.strip()
  915. cursect[optname] = [optval]
  916. else:
  917. # valueless option handling
  918. cursect[optname] = None
  919. else:
  920. # a non-fatal parsing error occurred. set up the
  921. # exception but keep going. the exception will be
  922. # raised at the end of the file and will contain a
  923. # list of all bogus lines
  924. e = self._handle_error(e, fpname, lineno, line)
  925. self._join_multiline_values()
  926. # if any parsing errors occurred, raise an exception
  927. if e:
  928. raise e
  929. def _join_multiline_values(self):
  930. defaults = self.default_section, self._defaults
  931. all_sections = itertools.chain((defaults,),
  932. self._sections.items())
  933. for section, options in all_sections:
  934. for name, val in options.items():
  935. if isinstance(val, list):
  936. val = '\n'.join(val).rstrip()
  937. options[name] = self._interpolation.before_read(self,
  938. section,
  939. name, val)
  940. def _read_defaults(self, defaults):
  941. """Read the defaults passed in the initializer.
  942. Note: values can be non-string."""
  943. for key, value in defaults.items():
  944. self._defaults[self.optionxform(key)] = value
  945. def _handle_error(self, exc, fpname, lineno, line):
  946. if not exc:
  947. exc = ParsingError(fpname)
  948. exc.append(lineno, repr(line))
  949. return exc
  950. def _unify_values(self, section, vars):
  951. """Create a sequence of lookups with 'vars' taking priority over
  952. the 'section' which takes priority over the DEFAULTSECT.
  953. """
  954. sectiondict = {}
  955. try:
  956. sectiondict = self._sections[section]
  957. except KeyError:
  958. if section != self.default_section:
  959. raise NoSectionError(section) from None
  960. # Update with the entry specific variables
  961. vardict = {}
  962. if vars:
  963. for key, value in vars.items():
  964. if value is not None:
  965. value = str(value)
  966. vardict[self.optionxform(key)] = value
  967. return _ChainMap(vardict, sectiondict, self._defaults)
  968. def _convert_to_boolean(self, value):
  969. """Return a boolean value translating from other types if necessary.
  970. """
  971. if value.lower() not in self.BOOLEAN_STATES:
  972. raise ValueError('Not a boolean: %s' % value)
  973. return self.BOOLEAN_STATES[value.lower()]
  974. def _validate_value_types(self, *, section="", option="", value=""):
  975. """Raises a TypeError for non-string values.
  976. The only legal non-string value if we allow valueless
  977. options is None, so we need to check if the value is a
  978. string if:
  979. - we do not allow valueless options, or
  980. - we allow valueless options but the value is not None
  981. For compatibility reasons this method is not used in classic set()
  982. for RawConfigParsers. It is invoked in every case for mapping protocol
  983. access and in ConfigParser.set().
  984. """
  985. if not isinstance(section, str):
  986. raise TypeError("section names must be strings")
  987. if not isinstance(option, str):
  988. raise TypeError("option keys must be strings")
  989. if not self._allow_no_value or value:
  990. if not isinstance(value, str):
  991. raise TypeError("option values must be strings")
  992. @property
  993. def converters(self):
  994. return self._converters
  995. class ConfigParser(RawConfigParser):
  996. """ConfigParser implementing interpolation."""
  997. _DEFAULT_INTERPOLATION = BasicInterpolation()
  998. def set(self, section, option, value=None):
  999. """Set an option. Extends RawConfigParser.set by validating type and
  1000. interpolation syntax on the value."""
  1001. self._validate_value_types(option=option, value=value)
  1002. super().set(section, option, value)
  1003. def add_section(self, section):
  1004. """Create a new section in the configuration. Extends
  1005. RawConfigParser.add_section by validating if the section name is
  1006. a string."""
  1007. self._validate_value_types(section=section)
  1008. super().add_section(section)
  1009. def _read_defaults(self, defaults):
  1010. """Reads the defaults passed in the initializer, implicitly converting
  1011. values to strings like the rest of the API.
  1012. Does not perform interpolation for backwards compatibility.
  1013. """
  1014. try:
  1015. hold_interpolation = self._interpolation
  1016. self._interpolation = Interpolation()
  1017. self.read_dict({self.default_section: defaults})
  1018. finally:
  1019. self._interpolation = hold_interpolation
  1020. class SectionProxy(MutableMapping):
  1021. """A proxy for a single section from a parser."""
  1022. def __init__(self, parser, name):
  1023. """Creates a view on a section of the specified `name` in `parser`."""
  1024. self._parser = parser
  1025. self._name = name
  1026. for conv in parser.converters:
  1027. key = 'get' + conv
  1028. getter = functools.partial(self.get, _impl=getattr(parser, key))
  1029. setattr(self, key, getter)
  1030. def __repr__(self):
  1031. return '<Section: {}>'.format(self._name)
  1032. def __getitem__(self, key):
  1033. if not self._parser.has_option(self._name, key):
  1034. raise KeyError(key)
  1035. return self._parser.get(self._name, key)
  1036. def __setitem__(self, key, value):
  1037. self._parser._validate_value_types(option=key, value=value)
  1038. return self._parser.set(self._name, key, value)
  1039. def __delitem__(self, key):
  1040. if not (self._parser.has_option(self._name, key) and
  1041. self._parser.remove_option(self._name, key)):
  1042. raise KeyError(key)
  1043. def __contains__(self, key):
  1044. return self._parser.has_option(self._name, key)
  1045. def __len__(self):
  1046. return len(self._options())
  1047. def __iter__(self):
  1048. return self._options().__iter__()
  1049. def _options(self):
  1050. if self._name != self._parser.default_section:
  1051. return self._parser.options(self._name)
  1052. else:
  1053. return self._parser.defaults()
  1054. @property
  1055. def parser(self):
  1056. # The parser object of the proxy is read-only.
  1057. return self._parser
  1058. @property
  1059. def name(self):
  1060. # The name of the section on a proxy is read-only.
  1061. return self._name
  1062. def get(self, option, fallback=None, *, raw=False, vars=None,
  1063. _impl=None, **kwargs):
  1064. """Get an option value.
  1065. Unless `fallback` is provided, `None` will be returned if the option
  1066. is not found.
  1067. """
  1068. # If `_impl` is provided, it should be a getter method on the parser
  1069. # object that provides the desired type conversion.
  1070. if not _impl:
  1071. _impl = self._parser.get
  1072. return _impl(self._name, option, raw=raw, vars=vars,
  1073. fallback=fallback, **kwargs)
  1074. class ConverterMapping(MutableMapping):
  1075. """Enables reuse of get*() methods between the parser and section proxies.
  1076. If a parser class implements a getter directly, the value for the given
  1077. key will be ``None``. The presence of the converter name here enables
  1078. section proxies to find and use the implementation on the parser class.
  1079. """
  1080. GETTERCRE = re.compile(r"^get(?P<name>.+)$")
  1081. def __init__(self, parser):
  1082. self._parser = parser
  1083. self._data = {}
  1084. for getter in dir(self._parser):
  1085. m = self.GETTERCRE.match(getter)
  1086. if not m or not callable(getattr(self._parser, getter)):
  1087. continue
  1088. self._data[m.group('name')] = None # See class docstring.
  1089. def __getitem__(self, key):
  1090. return self._data[key]
  1091. def __setitem__(self, key, value):
  1092. try:
  1093. k = 'get' + key
  1094. except TypeError:
  1095. raise ValueError('Incompatible key: {} (type: {})'
  1096. ''.format(key, type(key)))
  1097. if k == 'get':
  1098. raise ValueError('Incompatible key: cannot use "" as a name')
  1099. self._data[key] = value
  1100. func = functools.partial(self._parser._get_conv, conv=value)
  1101. func.converter = value
  1102. setattr(self._parser, k, func)
  1103. for proxy in self._parser.values():
  1104. getter = functools.partial(proxy.get, _impl=func)
  1105. setattr(proxy, k, getter)
  1106. def __delitem__(self, key):
  1107. try:
  1108. k = 'get' + (key or None)
  1109. except TypeError:
  1110. raise KeyError(key)
  1111. del self._data[key]
  1112. for inst in itertools.chain((self._parser,), self._parser.values()):
  1113. try:
  1114. delattr(inst, k)
  1115. except AttributeError:
  1116. # don't raise since the entry was present in _data, silently
  1117. # clean up
  1118. continue
  1119. def __iter__(self):
  1120. return iter(self._data)
  1121. def __len__(self):
  1122. return len(self._data)