ConfigObj method for listing sections containing subkeys

I use ConfigObj to parse a configuration file in the format:

[APACHE]
init_script=
...
[TOMCAT]
    [[TOMCAT1]]
    init_script =
    [[TOMCAT2]]
    init_script =

In some state, the [TOMCAT] section may have a nested subsection, sometimes more than one root [TOMCAT] instance.

I'm so interesting in python, there is a convenient way to go through the configuration file and get only those elements that contain nested subsection elements.

I am currently using this approach:

def is_section(config_section):
    """
       Check that config elemet is a section
    """
    try:
     config_section.keys()
    except AttributeError:
        return False
    else:
        return True
onfig = ConfigObj(config_file,list_values=True,interpolation=True)

sections = config.keys()

for section in sections:
     if is_section(config[section]):
        for subsection in config[section]:
            if is_section(config[section][subsection]):
                print  "Subsection ", subsection
+3
source share
1 answer

You can use the method walkand print section with depthmore than one.

def gather_subsection(section, key):
    if section.depth > 1:
        print "Subsection " + section.name

config.walk(gather_subsection)

Documentation for Depth

depth

The nesting level of the current section.

If you create a new ConfigObj and add sections, 1 will be added to the depth level between sections.

Documentation for walking

+4
source

Source: https://habr.com/ru/post/1791496/


All Articles