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

时间:2020-01-27 18:39:15

标签: python ini configparser

我要使用python内置的arr[0].pivot.id来解析conf文件中的布尔值。

示例:

configparser

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

[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 解析时,如何用最少的开销处理布尔值?

1 个答案:

答案 0 :(得分:2)

您要使用configparser,这是节对象上的函数。

例如

getboolean

Documentation

相关问题