简体   繁体   English

ConfigObj获取包含子节的节的列表的方法

[英]ConfigObj way to get list of sections that contain subsections

I use ConfigObj to parse config file in format: 我使用ConfigObj以格式解析配置文件:

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

In some condition [TOMCAT] section may have nested subsection,sometime not - only single root instance [TOMCAT] . 在某些情况下[TOMCAT]部分可能有嵌套的子部分,有时不是 - 只有单个根实例[TOMCAT]。

I'm fresh in python so interesting, is there a convenient way to walk through config file and get only elements that contain nested subsection elements. 我在python中很新鲜如此有趣,是否有一种方便的方法来遍历配置文件并只获取包含嵌套子节元素的元素。

Currently I use such 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

You can use the method walk and print section that have a depth greater than one. 您可以使用depth大于1的方法walk和print部分。

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. 如果您创建一个新的ConfigObj并添加部分,则将在部分之间的深度级别添加1。

Documentation for walk 步行文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM