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

How to parse boolean with config parser

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

示例:

[SECTION]
foo = False

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

>>> config['SECTION']['foo']
'False'

此外,当我尝试纠正此行为并将键 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                                                                                                                                                      

不幸的是,这种行为会导致出现以下问题,即意外执行

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

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

您想使用 getboolean,一个针对节对象的函数。

例如

>>> config['SECTION'].getboolean('foo')
False

Documentation