2012-10-05 82 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」。布爾( 「否」)爲真