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

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

但是,对于报告,我想知道该选项是在[specific]部分还是在[DEFAULT]中设置的.有没有办法用RawConfigParser的界面做到这一点,或者我没有选择,只能手动解析文件? (我已经看了一下,我开始担心最糟糕的……)

例如

[默认]

name = a

姓= b

[部分]

name = b

年龄= 23岁

你怎么知道,使用RawConfigParser界面,是否选项名称&姓氏是从[DEFAULT]或[SECTION]部分加载的?

(我知道[DEFAULT]适用于所有人,但你可能想在内部报告这样的事情,以便通过复杂的配置文件工作)

谢谢!

最佳答案 鉴于此配置文件:

[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']
点赞