迭代配置文件中的部分

Mar*_*ong 21 python configuration file configparser sections

我最近介绍了库configparser.我希望能够检查每个部分是否至少有一个布尔值设置为1.例如:

[Horizontal_Random_Readout_Size]
Small_Readout  = 0
Medium_Readout = 0
Large_Readout  = 0
Run Code Online (Sandbox Code Playgroud)

以上会导致错误.

[Vertical_Random_Readout_Size]
Small_Readout  = 0
Medium_Readout = 0
Large_Readout  = 1
Run Code Online (Sandbox Code Playgroud)

以上将通过.下面是我想到的一些伪代码:

exit_test = False
for sections in config_file:
    section_check = False
    for name in parser.options(section):
        if parser.getboolean(section, name):
            section_check = True
    if not section_check:
        print "ERROR:Please specify a setting in {} section of the config file".format(section)
        exit_test = True
    if exit_test:
        exit(1)
Run Code Online (Sandbox Code Playgroud)

问题:

1)如何执行第一个for循环并迭代配置文件的各个部分?

2)这是一个很好的方法吗?还是有更好的方法?(如果没有请回答问题一.)

Nil*_*esh 54

使用ConfigParser你必须解析你的配置.

解析后,您将使用.sections()方法获取所有部分.

您可以迭代每个部分并使用.items()获取每个部分的所有键/值对.

for each_section in conf.sections():
    for (each_key, each_val) in conf.items(each_section):
        print each_key
        print each_val
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“[DEFAULT]”部分不包含在“conf.sections()”返回的列表中 (3认同)