如何使用与模式匹配的节名称的configparser

2024-09-28 20:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用configparser读取一个INI文件,其中设置名称在文件的不同版本之间略有不同(取决于文件来自哪个分支)

因此,在某些文件中,节名称是:

[WEB - Component1_Build]
option1=foo
option2=bar

[WEB - Component2_Build]
option3=foo
option4=bar

[WEB - Component3_Build]
option5=foo
option6=bar

在上面的示例中,所有组件都是从“默认分支”构建的

但是在另一个文件中,同样的代码需要处理,节名称可以是:

[WEB - Component1_Build - my_feature_branch]
option1=foo
option2=bar

[WEB - Component2_Build]
option3=foo
option4=bar

[WEB - Component3_Build - my_feature_branch]
option5=foo
option6=bar

在上述示例中,组件1和;3是从要素分支生成的,但组件2是从“默认分支”生成的

另一个例子

[WEB - Component1_Build - prod_release_branch]
option1=foo
option2=bar

[WEB - Component2_Build - prod_release_branch]
option3=foo
option4=bar

[WEB - Component3_Build - prod_release_branch]
option5=foo
option6=bar

[WEB - Component4_Build - prod_release_branch]
option7=foo
option8=bar

在上面的示例中,有一个附加组件,但所有组件都是从发布分支构建的

在我的python代码中,我希望对节名使用一些级别或模式匹配或正则表达式,但我不确定如何做到这一点

我试图查找configparser.SECTCRE来定制解析器行为,但我不确定如何解决这个问题


config = configparser.ConfigParser()

# not sure if this is right
config.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")

config.read("my_ini_file.ini")
print(config.sections())

# this works, but I would want to fetch the section using component name
print(config.options(config.sections()[0]))

# this doesn't work and I get an error
# error is: configparser.NoSectionError: No section: '(Component1)+'
print(config.options(r'(Component1)+'))

# these work, but I would want to fetch the section using component name
print(config.get(config.sections()[0], 'option1'))
print(config.get(config.sections()[0], 'option2'))

error is: configparser.NoSectionError: No section: '(Component1)+'

Tags: 文件buildbranchwebconfigfoo分支bar