我试图找出为什么ConfigParser为get()方法提供Python类型,但items()提供所有字符串,如'True'而不是True等。
作为一种解决方法,我正在做这样的事情:
log_settings = dict(CONF.items('log'))
for key, value in log_settings.items():
log_settings[key] = CONF.get('log', key)
对此有何想法?
答案 0 :(得分:1)
来自ConfigParser
来源:
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()
如您所见,.items()
没有对数据进行后处理以将其转换为任何类型。
作为旁注,你确定.get
没有做同样的事情吗? .get
的源代码不会强制转换数据,而是.getboolean
和co。做。您确定没有使用.getboolean
或.getfloat
吗?
下面,您可以看到有一个帮助._get
函数调用.get
加上.getfloat
等转换。
def _get(self, section, conv, option):
return conv(self.get(section, option))
def getfloat(self, section, option):
return self._get(section, float, option)
.get
函数没有这样的转换(在.get
._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)
答案 1 :(得分:1)
虽然这已经得到了解答,但这是google for" python configparser .items parse boolean"
中的顶级stackoverflow结果因此,在解析时我需要布尔值,我想我会分享一些我正在使用的示例代码..它当然很简单,只是一个例子..但可能会节省一些时间或者给他们想法..
另请注意,这是在课堂上,所以忽略自我。如果你不使用它。
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]
无论如何,希望它可以帮助某人,请不要对编码标准发表评论......这仅用于显示目的....