简体   繁体   中英

Booleans in ConfigParser always return True

This is my example script:

import ConfigParser

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

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

And this is conf.ini :

[main]
some_boolean: yes
some_other_boolean: no

When running the script, it prints True twice. Why? It should be False , as some_other_boolean is set to no .

Use getboolean() :

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

From the Python manual :

 RawConfigParser.getboolean(section, option) 

A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are "1", "yes", "true", and "on", which cause this method to return True, and "0", "no", "false", and "off", which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError.

The bool() constructor converts an empty string to False. Non-empty strings are True. bool() doesn't do anything special for "false", "no", etc.

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

It returns the string "no". bool("no") is True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM