X-Git-Url: http://www.iramuteq.org/git?a=blobdiff_plain;f=configparser.py;h=11baaaf021df889a7f36787f78164821c5a4563b;hb=refs%2Fheads%2F3.0;hp=8e6280dfd0528e1470782fa4b16bffb33fd1e2ac;hpb=3f66309538f8393e15449aa1380430457ed864b7;p=iramuteq diff --git a/configparser.py b/configparser.py index 8e6280d..11baaaf 100644 --- a/configparser.py +++ b/configparser.py @@ -1,7 +1,7 @@ -#!/usr/bin/env python # -*- coding: utf-8 -*- +#modification pour python 3 : Laurent Mérat, 6x7 - mai 2020 -u"""Configuration file parser. +"""Configuration file parser. A configuration file consists of sections, lead by a "[section]" header, and followed by "name: value" entries, with continuations and such in @@ -122,30 +122,37 @@ ConfigParser -- responsible for parsing a list of between keys and values are surrounded by spaces. """ -from __future__ import with_statement -from collections import MutableMapping -from io import open -try: - from collections import OrderedDict as _default_dict -except ImportError: - from ordereddict import OrderedDict as _default_dict -import functools +#------------------------------------ +# import des modules python +#------------------------------------ +from collections.abc import MutableMapping import io import itertools import re import sys import warnings +#------------------------------------ +# import des fichiers du projet +#------------------------------------ from configparser_helpers import _ChainMap -__all__ = [u"NoSectionError", u"DuplicateOptionError", u"DuplicateSectionError", - u"NoOptionError", u"InterpolationError", u"InterpolationDepthError", - u"InterpolationSyntaxError", u"ParsingError", - u"MissingSectionHeaderError", - u"ConfigParser", u"SafeConfigParser", u"RawConfigParser", - u"DEFAULTSECT", u"MAX_INTERPOLATION_DEPTH"] -DEFAULTSECT = u"DEFAULT" +try: + from collections import OrderedDict as _default_dict +except ImportError: + from ordereddict import OrderedDict as _default_dict +import functools + + +__all__ = ["NoSectionError", "DuplicateOptionError", "DuplicateSectionError", + "NoOptionError", "InterpolationError", "InterpolationDepthError", + "InterpolationSyntaxError", "ParsingError", + "MissingSectionHeaderError", + "ConfigParser", "SafeConfigParser", "RawConfigParser", + "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"] + +DEFAULTSECT = "DEFAULT" MAX_INTERPOLATION_DEPTH = 10 @@ -153,16 +160,16 @@ MAX_INTERPOLATION_DEPTH = 10 # exception classes class Error(Exception): - u"""Base class for ConfigParser exceptions.""" + """Base class for ConfigParser exceptions.""" def _get_message(self): - u"""Getter for 'message'; needed only to override deprecation in + """Getter for 'message'; needed only to override deprecation in BaseException. """ return self.__message def _set_message(self, value): - u"""Setter for 'message'; needed only to override deprecation in + """Setter for 'message'; needed only to override deprecation in BaseException. """ self.__message = value @@ -172,7 +179,7 @@ class Error(Exception): # a new property that takes lookup precedence. message = property(_get_message, _set_message) - def __init__(self, msg=u''): + def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg) @@ -183,16 +190,16 @@ class Error(Exception): class NoSectionError(Error): - u"""Raised when no section matches a requested option.""" + """Raised when no section matches a requested option.""" def __init__(self, section): - Error.__init__(self, u'No section: %r' % (section,)) + Error.__init__(self, 'No section: %r' % (section,)) self.section = section self.args = (section, ) class DuplicateSectionError(Error): - u"""Raised when a section is repeated in an input source. + """Raised when a section is repeated in an input source. Possible repetitions that raise this exception are: multiple creation using the API or in strict parsers when a section is found more than once @@ -200,17 +207,17 @@ class DuplicateSectionError(Error): """ def __init__(self, section, source=None, lineno=None): - msg = [repr(section), u" already exists"] + msg = [repr(section), " already exists"] if source is not None: - message = [u"While reading from ", source] + message = ["While reading from ", source] if lineno is not None: - message.append(u" [line {0:2d}]".format(lineno)) - message.append(u": section ") + message.append(" [line {0:2d}]".format(lineno)) + message.append(": section ") message.extend(msg) msg = message else: - msg.insert(0, u"Section ") - Error.__init__(self, u"".join(msg)) + msg.insert(0, "Section ") + Error.__init__(self, "".join(msg)) self.section = section self.source = source self.lineno = lineno @@ -218,25 +225,25 @@ class DuplicateSectionError(Error): class DuplicateOptionError(Error): - u"""Raised by strict parsers when an option is repeated in an input source. + """Raised by strict parsers when an option is repeated in an input source. Current implementation raises this exception only when an option is found more than once in a single file, string or dictionary. """ def __init__(self, section, option, source=None, lineno=None): - msg = [repr(option), u" in section ", repr(section), - u" already exists"] + msg = [repr(option), " in section ", repr(section), + " already exists"] if source is not None: - message = [u"While reading from ", source] + message = ["While reading from ", source] if lineno is not None: - message.append(u" [line {0:2d}]".format(lineno)) - message.append(u": option ") + message.append(" [line {0:2d}]".format(lineno)) + message.append(": option ") message.extend(msg) msg = message else: - msg.insert(0, u"Option ") - Error.__init__(self, u"".join(msg)) + msg.insert(0, "Option ") + Error.__init__(self, "".join(msg)) self.section = section self.option = option self.source = source @@ -245,10 +252,10 @@ class DuplicateOptionError(Error): class NoOptionError(Error): - u"""A requested option was not found.""" + """A requested option was not found.""" def __init__(self, option, section): - Error.__init__(self, u"No option %r in section: %r" % + Error.__init__(self, "No option %r in section: %r" % (option, section)) self.option = option self.section = section @@ -256,7 +263,7 @@ class NoOptionError(Error): class InterpolationError(Error): - u"""Base class for interpolation-related exceptions.""" + """Base class for interpolation-related exceptions.""" def __init__(self, option, section, msg): Error.__init__(self, msg) @@ -266,14 +273,14 @@ class InterpolationError(Error): class InterpolationMissingOptionError(InterpolationError): - u"""A string substitution required a setting which was not available.""" + """A string substitution required a setting which was not available.""" def __init__(self, option, section, rawval, reference): - msg = (u"Bad value substitution:\n" - u"\tsection: [%s]\n" - u"\toption : %s\n" - u"\tkey : %s\n" - u"\trawval : %s\n" + msg = ("Bad value substitution:\n" + "\tsection: [%s]\n" + "\toption : %s\n" + "\tkey : %s\n" + "\trawval : %s\n" % (section, option, reference, rawval)) InterpolationError.__init__(self, option, section, msg) self.reference = reference @@ -281,7 +288,7 @@ class InterpolationMissingOptionError(InterpolationError): class InterpolationSyntaxError(InterpolationError): - u"""Raised when the source text contains invalid syntax. + """Raised when the source text contains invalid syntax. Current implementation raises this exception when the source text into which substitutions are made does not conform to the required syntax. @@ -289,68 +296,68 @@ class InterpolationSyntaxError(InterpolationError): class InterpolationDepthError(InterpolationError): - u"""Raised when substitutions are nested too deeply.""" + """Raised when substitutions are nested too deeply.""" def __init__(self, option, section, rawval): - msg = (u"Value interpolation too deeply recursive:\n" - u"\tsection: [%s]\n" - u"\toption : %s\n" - u"\trawval : %s\n" + msg = ("Value interpolation too deeply recursive:\n" + "\tsection: [%s]\n" + "\toption : %s\n" + "\trawval : %s\n" % (section, option, rawval)) InterpolationError.__init__(self, option, section, msg) self.args = (option, section, rawval) class ParsingError(Error): - u"""Raised when a configuration file does not follow legal syntax.""" + """Raised when a configuration file does not follow legal syntax.""" def __init__(self, source=None, filename=None): # Exactly one of `source'/`filename' arguments has to be given. # `filename' kept for compatibility. if filename and source: - raise ValueError(u"Cannot specify both `filename' and `source'. " - u"Use `source'.") + raise ValueError("Cannot specify both `filename' and `source'. " + "Use `source'.") elif not filename and not source: - raise ValueError(u"Required argument `source' not given.") + raise ValueError("Required argument `source' not given.") elif filename: source = filename - Error.__init__(self, u'Source contains parsing errors: %s' % source) + Error.__init__(self, 'Source contains parsing errors: %s' % source) self.source = source self.errors = [] self.args = (source, ) @property def filename(self): - u"""Deprecated, use `source'.""" + """Deprecated, use `source'.""" warnings.warn( - u"The 'filename' attribute will be removed in future versions. " - u"Use 'source' instead.", + "The 'filename' attribute will be removed in future versions. " + "Use 'source' instead.", DeprecationWarning, stacklevel=2 ) return self.source @filename.setter def filename(self, value): - u"""Deprecated, user `source'.""" + """Deprecated, user `source'.""" warnings.warn( - u"The 'filename' attribute will be removed in future versions. " - u"Use 'source' instead.", + "The 'filename' attribute will be removed in future versions. " + "Use 'source' instead.", DeprecationWarning, stacklevel=2 ) self.source = value def append(self, lineno, line): self.errors.append((lineno, line)) - self.message += u'\n\t[line %2d]: %s' % (lineno, line) + self.message += '\n\t[line %2d]: %s' % (lineno, line) class MissingSectionHeaderError(ParsingError): - u"""Raised when a key-value pair is found before any section header.""" + """Raised when a key-value pair is found before any section header.""" def __init__(self, filename, lineno, line): Error.__init__( self, - u'File contains no section headers.\nfile: %s, line: %d\n%r' % + 'File contains no section headers.\nfile: %s, line: %d\n%r' % (filename, lineno, line)) self.source = filename self.lineno = lineno @@ -365,7 +372,7 @@ _UNSET = object() class Interpolation(object): - u"""Dummy interpolation that passes the value through with no changes.""" + """Dummy interpolation that passes the value through with no changes.""" def before_get(self, parser, section, option, value, defaults): return value @@ -381,7 +388,7 @@ class Interpolation(object): class BasicInterpolation(Interpolation): - u"""Interpolation as implemented in the classic ConfigParser. + """Interpolation as implemented in the classic ConfigParser. The option values can contain format strings which refer to other values in the same section, or values in the special default section. @@ -395,19 +402,19 @@ class BasicInterpolation(Interpolation): a configuration file, she can escape it by writing %%. Other other % usage is considered a user error and raises `InterpolationSyntaxError'.""" - _KEYCRE = re.compile(ur"%\(([^)]+)\)s") + _KEYCRE = re.compile(r"%\(([^)]+)\)s") def before_get(self, parser, section, option, value, defaults): L = [] self._interpolate_some(parser, option, L, value, section, defaults, 1) - return u''.join(L) + return ''.join(L) def before_set(self, parser, section, option, value): - tmp_value = value.replace(u'%%', u'') # escaped percent signs - tmp_value = self._KEYCRE.sub(u'', tmp_value) # valid syntax - if u'%' in tmp_value: - raise ValueError(u"invalid interpolation syntax in %r at " - u"position %d" % (value, tmp_value.find(u'%'))) + tmp_value = value.replace('%%', '') # escaped percent signs + tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax + if '%' in tmp_value: + raise ValueError("invalid interpolation syntax in %r at " + "position %d" % (value, tmp_value.find('%'))) return value def _interpolate_some(self, parser, option, accum, rest, section, map, @@ -415,7 +422,7 @@ class BasicInterpolation(Interpolation): if depth > MAX_INTERPOLATION_DEPTH: raise InterpolationDepthError(option, section, rest) while rest: - p = rest.find(u"%") + p = rest.find("%") if p < 0: accum.append(rest) return @@ -424,14 +431,14 @@ class BasicInterpolation(Interpolation): rest = rest[p:] # p is no longer used c = rest[1:2] - if c == u"%": - accum.append(u"%") + if c == "%": + accum.append("%") rest = rest[2:] - elif c == u"(": + elif c == "(": m = self._KEYCRE.match(rest) if m is None: raise InterpolationSyntaxError(option, section, - u"bad interpolation variable reference %r" % rest) + "bad interpolation variable reference %r" % rest) var = parser.optionxform(m.group(1)) rest = rest[m.end():] try: @@ -439,7 +446,7 @@ class BasicInterpolation(Interpolation): except KeyError: raise InterpolationMissingOptionError( option, section, rest, var) - if u"%" in v: + if "%" in v: self._interpolate_some(parser, option, accum, v, section, map, depth + 1) else: @@ -447,27 +454,27 @@ class BasicInterpolation(Interpolation): else: raise InterpolationSyntaxError( option, section, - u"'%%' must be followed by '%%' or '(', " - u"found: %r" % (rest,)) + "'%%' must be followed by '%%' or '(', " + "found: %r" % (rest,)) class ExtendedInterpolation(Interpolation): - u"""Advanced variant of interpolation, supports the syntax used by + """Advanced variant of interpolation, supports the syntax used by `zc.buildout'. Enables interpolation between sections.""" - _KEYCRE = re.compile(ur"\$\{([^}]+)\}") + _KEYCRE = re.compile(r"\$\{([^}]+)\}") def before_get(self, parser, section, option, value, defaults): L = [] self._interpolate_some(parser, option, L, value, section, defaults, 1) - return u''.join(L) + return ''.join(L) def before_set(self, parser, section, option, value): - tmp_value = value.replace(u'$$', u'') # escaped dollar signs - tmp_value = self._KEYCRE.sub(u'', tmp_value) # valid syntax - if u'$' in tmp_value: - raise ValueError(u"invalid interpolation syntax in %r at " - u"position %d" % (value, tmp_value.find(u'%'))) + tmp_value = value.replace('$$', '') # escaped dollar signs + tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax + if '$' in tmp_value: + raise ValueError("invalid interpolation syntax in %r at " + "position %d" % (value, tmp_value.find('%'))) return value def _interpolate_some(self, parser, option, accum, rest, section, map, @@ -475,7 +482,7 @@ class ExtendedInterpolation(Interpolation): if depth > MAX_INTERPOLATION_DEPTH: raise InterpolationDepthError(option, section, rest) while rest: - p = rest.find(u"$") + p = rest.find("$") if p < 0: accum.append(rest) return @@ -484,15 +491,15 @@ class ExtendedInterpolation(Interpolation): rest = rest[p:] # p is no longer used c = rest[1:2] - if c == u"$": - accum.append(u"$") + if c == "$": + accum.append("$") rest = rest[2:] - elif c == u"{": + elif c == "{": m = self._KEYCRE.match(rest) if m is None: raise InterpolationSyntaxError(option, section, - u"bad interpolation variable reference %r" % rest) - path = m.group(1).split(u':') + "bad interpolation variable reference %r" % rest) + path = m.group(1).split(':') rest = rest[m.end():] sect = section opt = option @@ -507,11 +514,11 @@ class ExtendedInterpolation(Interpolation): else: raise InterpolationSyntaxError( option, section, - u"More than one ':' found: %r" % (rest,)) + "More than one ':' found: %r" % (rest,)) except (KeyError, NoSectionError, NoOptionError): raise InterpolationMissingOptionError( - option, section, rest, u":".join(path)) - if u"$" in v: + option, section, rest, ":".join(path)) + if "$" in v: self._interpolate_some(parser, opt, accum, v, sect, dict(parser.items(sect, raw=True)), depth + 1) @@ -520,33 +527,33 @@ class ExtendedInterpolation(Interpolation): else: raise InterpolationSyntaxError( option, section, - u"'$' must be followed by '$' or '{', " - u"found: %r" % (rest,)) + "'$' must be followed by '$' or '{', " + "found: %r" % (rest,)) class LegacyInterpolation(Interpolation): - u"""Deprecated interpolation used in old versions of ConfigParser. + """Deprecated interpolation used in old versions of ConfigParser. Use BasicInterpolation or ExtendedInterpolation instead.""" - _KEYCRE = re.compile(ur"%\(([^)]*)\)s|.") + _KEYCRE = re.compile(r"%\(([^)]*)\)s|.") def before_get(self, parser, section, option, value, vars): rawval = value depth = MAX_INTERPOLATION_DEPTH while depth: # Loop through this until it's done depth -= 1 - if value and u"%(" in value: + if value and "%(" in value: replace = functools.partial(self._interpolation_replace, parser=parser) value = self._KEYCRE.sub(replace, value) try: value = value % vars - except KeyError, e: + except KeyError as e: raise InterpolationMissingOptionError( option, section, rawval, e.args[0]) else: break - if value and u"%(" in value: + if value and "%(" in value: raise InterpolationDepthError(option, section, rawval) return value @@ -559,19 +566,19 @@ class LegacyInterpolation(Interpolation): if s is None: return match.group() else: - return u"%%(%s)s" % parser.optionxform(s) + return "%%(%s)s" % parser.optionxform(s) class RawConfigParser(MutableMapping): - u"""ConfigParser that does not do interpolation.""" + """ConfigParser that does not do interpolation.""" # Regular expressions for parsing section headers and options - _SECT_TMPL = ur""" + _SECT_TMPL = r""" \[ # [ (?P
[^]]+) # very permissive! \] # ] """ - _OPT_TMPL = ur""" + _OPT_TMPL = r""" (?P