Domanda

I'm trying to figure out why ConfigParser is giving Python types for the get() method, but items() is giving all strings, like 'True' instead of True, etc.

As a workaround I'm doing something like this:

log_settings = dict(CONF.items('log'))
for key, value in log_settings.items():
    log_settings[key] = CONF.get('log', key)

Any thoughts on this?

È stato utile?

Soluzione

From the ConfigParser source:

def items(self, section):
    try:
        d2 = self._sections[section]
    except KeyError:
        if section != DEFAULTSECT:
            raise NoSectionError(section)
        d2 = self._dict()
    d = self._defaults.copy()
    d.update(d2)
    if "__name__" in d:
        del d["__name__"]
    return d.items()

As you can see, .items() does no post-processing of the data to convert it to any type.


As a side note, are you sure .get isn't doing the same thing? The source code for .get does no coercing of the data, but .getboolean and co. do. Are you sure you aren't using .getboolean or .getfloat?

Below, you can see there is a helper ._get function that calls .get plus a conversion for the .getfloat etc.

def _get(self, section, conv, option):
    return conv(self.get(section, option))

def getfloat(self, section, option):
    return self._get(section, float, option)

The .get function has no such converion (it is done after .get in ._get)

def get(self, section, option):
    opt = self.optionxform(option)
    if section not in self._sections:
        if section != DEFAULTSECT:
            raise NoSectionError(section)
        if opt in self._defaults:
            return self._defaults[opt]
        else:
            raise NoOptionError(option, section)
    elif opt in self._sections[section]:
        return self._sections[section][opt]
    elif opt in self._defaults:
        return self._defaults[opt]
    else:
        raise NoOptionError(option, section)

Altri suggerimenti

While this has already been answered, this was the top stackoverflow result in google for "python configparser .items parse boolean"

So being that i need booleans at the time of parsing, i thought i would share some example code that i'm using.. It of course is simple and only an example.. But might save someone some time or give them ideas..

Also note this is in a class, so ignore the self. if your not using one.

self.ConfigManager = ConfigParser.RawConfigParser()
self.ConfigManager.read('settings.ini')
listConfigSections = self.ConfigManager.sections()
for cfgSection in listConfigSections:
    self.Settings[cfgSection] = {}
    for cfgItem in self.ConfigManager.items(cfgSection):
        if str(cfgItem[1]).lower()=="true":
            self.Settings[cfgSection][cfgItem[0]] = True                    
        elif str(cfgItem[1]).lower()=="false":
            self.Settings[cfgSection][cfgItem[0]] = False                   
        else:
            self.Settings[cfgSection][cfgItem[0]] = cfgItem[1]                  

Anyway, hope it helps someone and please no comments on coding standards.. this is only for display purposes....

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top