gpt4 book ai didi

python - ConfigParser 中的 boolean 值总是返回 True

转载 作者:太空狗 更新时间:2023-10-29 17:26:18 24 4
gpt4 key购买 nike

这是我的示例脚本:

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

最佳答案

使用getboolean() :

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

来自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.

如:

my_bool = config.getboolean('SECTION','IDENTIFIER')

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

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

关于python - ConfigParser 中的 boolean 值总是返回 True,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12750778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com