Вопрос

Я недавно познакомился с библиотекой ConfigParser.Я хотел бы иметь возможность проверить, есть ли каждый раздел, по крайней мере, одним логическим значением, установленным на 1. Например:

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

Приведенное выше вызвало бы ошибку.

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

Приведенный выше пройдет.Ниже приведен какой-то псевдовый код того, что я имел в виду:

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)
.

Вопросы:

1) Как я могу выполнять первое для цикла и итерации по разделам файла конфигурации?

2) Это хороший способ сделать это или есть лучший способ?(Если нет, пожалуйста, ответьте на вопрос один.)

Это было полезно?

Решение

Использование ConfigParser Вы должны разбирать конфигурацию.

После анализа вы получите все разделы, используя все разделы, используя generacodiccode Способ.

Вы можете повторить каждый раздел и использовать generacodiccode Чтобы получить все пары ключа / значения каждого раздела.

for each_section in conf.sections():
    for (each_key, each_val) in conf.items(each_section):
        print each_key
        print each_val
.

Другие советы

Best bet is to load ALL the lines in the file into some kind of array (I'm going to ignore the issue of how much memory that might use and whether to page through it instead).

Then from there you know that lines denoting headings follow a certain format, so you can iterate over your array to create an array of objects containing the heading name; the line index (zero based reference to master array) and whether that heading has a value set.

From there you can iterate over these objects in cross-reference to the master array, and for each heading check the next "n" lines (in the master array) between the current heading and the next.

At this point you're down to the individual config values for that heading so you should easily be able to parse the line and detect a value, whereupon you can break from the loop if true, or for more robustness issue an exclusivity check on those heading's values in order to ensure ONLY one value is set.

Using this approach you have access to all the lines, with one object per heading, so your code remains flexible and functional. Optimise afterwards.

Hope that makes sense and is helpful.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top