Question

J'ai récemment découvert le configparser de la bibliothèque.J'aimerais pouvoir vérifier si chaque section a au moins une valeur booléenne définie sur 1.Par exemple:

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

Ce qui précède provoquerait une erreur.

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

Ce qui précède passerait.Vous trouverez ci-dessous un pseudo-code de ce que j'avais en tête :

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)

Des questions:

1) Comment effectuer la première boucle for et parcourir les sections du fichier de configuration ?

2) Est-ce une bonne façon de procéder ou existe-t-il une meilleure façon de procéder ?(S'il n'y en a pas, veuillez répondre à la première question.)

Était-ce utile?

La solution

En utilisant ConfigParser vous devez analyser votre configuration.

Après l'analyse, vous obtiendrez toutes les sections en utilisant .sections() méthode.

Vous pouvez parcourir chaque section et utiliser .items() pour obtenir toutes les paires clé/valeur de chaque section.

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

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top