def interpolate( self, s, section=DEFAULTSECT, name="<variable>" ): """Interpolates config variable references in the string Any reference of the form :samp:`%({variable-name})s` will be replaced with the appropriate value form the configuration file. :param s: The string into which values should be interpolated :type s: str :returns: str -- The value of `s` after interpolation """ ### This code is copied wholesale from the ConfigParser class. It makes use of that class's non-public ### _interpolate() method sectiondict = {} try: sectiondict = self._sections[section] except KeyError: pass # By doing nothing, we will interpolate from the defaults # Update with the entry specific variables d = _Chainmap(sectiondict, self._defaults) name = self.optionxform( name ) if s is None: return s else: return self._interpolate(section, name, s, d)
def get(self, option, raw=True, variables=None, section=None): """ Overwrite the original method to get an option value for the given section. """ sectiondict = {} try: sectiondict = self._sections[self.section] except KeyError: if self.section != DEFAULTSECT: raise NoConfigSection() # Update with the entry specific variables vardict = {} if variables: for key, value in variables.items(): vardict[self.optionxform(key)] = value d = _Chainmap(vardict, sectiondict, self._defaults) option = self.optionxform(option) try: value = d[option] except KeyError: raise NoConfigOption(option) if raw or value is None: return value else: return self._interpolate(self.section, option, value, d)
def diff_ini(first, second, diff=None, existing_only=False): """Diff ini files Generate a parser with any value in the second that is different in the first. Returns a ConfigParser. Takes interpolation into account. Does not include values that disappeared.""" from ConfigParser import _Chainmap first = asParser(first) second = asParser(second) # TODO: Look at first both in raw and formatted versions diff = diff or Parser() interpolating = SafeConfigParser() for section in second.sections(): if section != 'DEFAULT' and not first.has_section(section): if not existing_only: diff.add_section(section) for option in second.options(section): value = second.get(section, option) diff.set(section, option, value) else: vars = _Chainmap(second._sections[section], first._sections[section], second._defaults, first._defaults) for option, value2 in second.items(section): if not first.has_option(section, option): if not existing_only: ensureSection(diff, section) diff.set(section, option, value2) continue value1 = first.get(section, option) if value1 != value2 and '%(' in value1: # try to interpolate, and see if it would amount to the same. try: value1 = interpolating._interpolate( section, option, value1, vars) except Exception as e: pass if value1 != value2: ensureSection(diff, section) diff.set(section, option, value2) return diff