如何使用配置解析器解析布尔值

Har*_*oli 3 python ini configparser

使用 python 的内置函数configparser,我想解析我的conf文件中的布尔值。

例子:

[SECTION]
foo = False
Run Code Online (Sandbox Code Playgroud)

但是,当访问变量时,我注意到它被作为字符串处理。

>>> config['SECTION']['foo']
'False'
Run Code Online (Sandbox Code Playgroud)

此外,当我尝试纠正此行为并将密钥重新分配foo给它正确的布尔代表时,我收到此错误

>>>         if config['SECTION']['foo'] == 'True':
...             config['SECTION']['foo'] = True
...         elif config['SECTION']['foo'] == 'False':                                                                                                                                      
...             config['SECTION']['foo'] = False
...         else:                                    
...             Exception("foo must be bool")
TypeError: option values must be strings                                                                                                                                                      
Run Code Online (Sandbox Code Playgroud)

不幸的是,这种行为会导致出现以下问题:

print(config['SECTION']['foo']) # 'False'

if config['SECTION']['foo']:
   print('do things when foo is True') # this runs, but foo actually 
                                       # represents false, but in string form
Run Code Online (Sandbox Code Playgroud)

在解析时我应该如何以configparser尽可能少的开销处理布尔值?

Har*_*oli 6

getboolean您想在节对象上使用,一个函数。

例如

>>> config['SECTION'].getboolean('foo')
False
Run Code Online (Sandbox Code Playgroud)

文档