3

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

但是,对于报告,我想知道该选项是在 [特定] 部分还是在 [DEFAULT] 中设置的。有什么办法可以通过 RawConfigParser 的接口来做到这一点,还是我别无选择,只能手动解析文件?(我已经找了一点,我开始担心最坏的情况......)

例如

[默认]

名字=一个

姓氏 = b

[部分]

名称 = b

年龄 = 23

你怎么知道,使用 RawConfigParser 接口,选项 name 和 surname 是从 [DEFAULT] 部分还是 [SECTION] 部分加载的?

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

谢谢!

4

3 回答 3

5

我最近通过将选项制作成字典,然后合并字典来做到这一点。它的巧妙之处在于用户参数覆盖了默认值,并且很容易将它们全部传递给函数。

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())
于 2012-11-20T10:25:57.830 回答
2

鉴于此配置文件:

[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']
于 2010-03-16T03:06:23.570 回答
0

RawConfigParser.has_option(section, option)做作业?

于 2010-02-22T13:36:03.787 回答