Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over sections in a config file

I recently got introduced to the library configparser. I would like to be able to check if each section has at least one Boolean value set to 1. For example:

[Horizontal_Random_Readout_Size]
Small_Readout  = 0
Medium_Readout = 0
Large_Readout  = 0

The above would cause an error.

[Vertical_Random_Readout_Size]
Small_Readout  = 0
Medium_Readout = 0
Large_Readout  = 1

The above would pass. Below is some pseudo code of what I had in mind:

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)

Questions:

1) How do I perform the first for loop and iterate over the sections of the config file?

2) Is this a good way of doing this or is there a better way? (If there isn't please answer question one.)

like image 382
Marmstrong Avatar asked Feb 27 '14 12:02

Marmstrong


1 Answers

Using ConfigParser you have to parse your config.

After parsing you will get all sections using .sections() method.

You can iterate over each section and use .items() to get all key/value pairs of each section.

for each_section in conf.sections():
    for (each_key, each_val) in conf.items(each_section):
        print each_key
        print each_val
like image 131
Nilesh Avatar answered Nov 05 '22 20:11

Nilesh