Python ConfigParser:如何解决特定部分中设置的选项(而不是默认选项)

2024-05-23 20:09:02 发布

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

我有一个使用标准ConfigParser库中的RawConfigParser读取的配置文件。我的配置文件有一个[DEFAULT]节,后面跟着一个[specific]节。当我循环浏览[特定]部分中的选项时,它包括[默认]下的选项,这就是要发生的事情。

但是,对于报告,我想知道选项是在[特定]部分还是在[默认]中设置的。使用RawConfigParser的接口有什么方法可以做到这一点吗?或者我除了手动解析文件之外别无选择吗?(我已经找了一点,我开始害怕最坏的情况……)

例如

[默认]

名称=a

姓氏=b

[章节]

名称=b

年龄=23岁

使用RawConfigParser接口,您如何知道选项名称和姓氏是从section[DEFAULT]还是section[section]加载的?

(我知道[DEFAULT]应该应用于所有人,但您可能希望在内部报告类似的事情,以便在复杂的配置文件中工作)

谢谢!


Tags: 文件方法名称default标准配置文件选项报告
3条回答

给定此配置文件:

[DEFAULT]
name = a
surname = b

[Section 1]
name  = section 1 name
age = 23
#we should get a surname value from defaults

[Section 2]
name = section 2 name
surname = section 2 surname
age = 24

下面的程序可以理解第1节使用的是默认的姓氏属性。

import ConfigParser

parser = ConfigParser.RawConfigParser()
parser.read("config.ini")
#Do your normal config processing here
#When it comes time to audit default vs. explicit,
#clear the defaults
parser._defaults = {}
#Now you will see which options were explicitly defined
print parser.options("Section 1")
print parser.options("Section 2")

结果如下:

['age', 'name']
['age', 'surname', 'name']

不是RawConfigParser.has_option(section, option)做的吗?

最近,我通过将选项放入词典中,然后合并词典来实现这一点。它的精妙之处在于,用户参数会覆盖默认值,而且很容易将它们全部传递给函数。

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('config.ini')

defaultparam = {k:v for k,v in config.items('DEFAULT')}
userparam = {k:v for k,v in config.items('Section 1')}

mergedparam = dict(defaultparam.items() + userparam.items())

相关问题 更多 >