python - ConfigObj 获取包含子部分的部分列表的方法

标签 python parsing

我使用 ConfigObj 来解析格式的配置文件:

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

在某些情况下 [TOMCAT] 部分可能有嵌套子部分,有时不是 - 只有单个根实例 [TOMCAT] 。

我刚接触 python 很有趣,有没有一种方便的方法来遍历配置文件并只获取包含嵌套子节元素的元素。

目前我使用这样的方法:

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

最佳答案

您可以使用 walk 方法并打印 depth 大于 1 的部分。

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 walk

关于python - ConfigObj 获取包含子部分的部分列表的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4970098/

相关文章:

具有多个函数的 Python C 扩展

python - 如何使用Python中的套接字在两个设备之间发送数据?

python - ValueError : x and y must have same first dimension, 但形状为 (10, 1) 和 (90,)

python - Python 中的参数解析(必需与可选)

c - C 中变量的括号标识符

c++ - 需要 C++ 解析器

python - 有没有一种简单的方法可以使脚本准确地模仿python可执行文件的功能,以供在PyInstaller部署中使用?

python - 替换分发版 python 脚本中的符号

java - Jackson API - 使用简单的动态对象反序列化 JSON

Python:SGMLParser 无法获取行号