Python 为什么ConfigParser items()提供原始字符串,而get()返回bool/float/etc?
我试图弄明白为什么ConfigParser为get()方法提供Python类型,而items()提供所有字符串,比如“True”而不是True,等等 作为解决办法,我正在做如下工作:Python 为什么ConfigParser items()提供原始字符串,而get()返回bool/float/etc?,python,python-2.7,configparser,Python,Python 2.7,Configparser,我试图弄明白为什么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) 对此有何想法?来自ConfigParser来源: def item
log_settings = dict(CONF.items('log'))
for key, value in log_settings.items():
log_settings[key] = CONF.get('log', key)
对此有何想法?来自
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.do。您确定没有使用.getboolean
或.getfloat
在下面,您可以看到一个helper\u 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
函数没有这样的转换(它是在\u get
中的.get
之后完成的)
虽然这已经得到了回答,但这是google中“PythonConfigParser.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]
无论如何,希望它能帮助一些人,请不要对编码标准发表评论。。这只是为了展示……谢谢,你说得对。。。事实证明,我的主要问题是我在使用别人的代码时没有意识到它是如何工作的。我正在使用Spyder作为在PyQt应用程序中进行配置管理的示例。。。事实证明,它们是ConfigParser的子类,并覆盖get方法。看起来他们这样做是为了允许eval解析复杂数据,因为他们在原始模式下运行ConfigParser。要明确的是,我的问题的真正根源是我使用了ConfigParser的一个子类,该子类在没有实现的情况下覆盖了get()函数。我还没有完全理解它就在使用它。谢谢你的贡献!这些天,如果有人向我提出这样的问题,要求我推荐JSON或YAML,而不是INI文件。利与弊,但我认为更好地支持分层数据是可取的。让YAML以我想要的方式使用OrderedDict需要一些工作,但我喜欢结果。别误会,JSON是我的主流方法。只是需要更新和转换的现有项目。
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]