2012-10-05 84 views
6

这是我的示例脚本:布尔在ConfigParser总是返回True

import ConfigParser 

config = ConfigParser.ConfigParser() 
config.read('conf.ini') 

print bool(config.get('main', 'some_boolean')) 
print bool(config.get('main', 'some_other_boolean')) 

这是conf.ini

[main] 
some_boolean: yes 
some_other_boolean: no 

运行脚本时,它打印True两次。为什么?它应该是False,因为some_other_boolean设置为no

回答

18

使用getboolean()

print config.getboolean('main', 'some_boolean') 
print config.getboolean('main', 'some_other_boolean') 

Python manual

RawConfigParser.getboolean(section, option) 

其胁迫在指定的部分中的选项为布尔值的简便方法。请注意,该选项的可接受值为“1”,“yes”,“true”和“on”,这会导致此方法返回True,并且“0”,“no”,“false”和“off “,导致它返回False。这些字符串值以不区分大小写的方式进行检查。任何其他值都会导致它引发ValueError。

bool()构造函数将空字符串转换为False。非空字符串为True。 bool()对“false”,“no”等不做任何特殊处理。

>>> bool('false') 
True 
>>> bool('no') 
True 
>>> bool('0') 
True 
>>> bool('') 
False 
+0

bah我有几乎相同的一组示例字符串... –

1

它返回字符串“no”。布尔( “否”)为真