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