Python ConfigParser:如何获取特定 section 中设置的选项(而非默认值)

3 投票
3 回答
8290 浏览
提问于 2025-04-15 19:34

我有一个配置文件,我是通过标准的 ConfigParser 库里的 RawConfigParser 来读取这个文件的。我的配置文件里有一个 [DEFAULT] 部分,后面跟着一个 [specific] 部分。当我循环遍历 [specific] 部分的选项时,它会包含 [DEFAULT] 部分的选项,这正是我想要的结果。

不过,在做报告的时候,我想知道某个选项是在哪个部分设置的,是在 [specific] 部分还是在 [DEFAULT] 部分。请问有没有办法通过 RawConfigParser 的接口来做到这一点,还是说我只能手动解析这个文件?(我查找了一下,开始有点担心了……)

举个例子:

[DEFAULT]

name = a

surname = b

[SECTION]

name = b

age = 23

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

(我知道 [DEFAULT] 是适用于所有的,但在处理复杂的配置文件时,你可能想要内部报告这些信息)

谢谢!

3 个回答

0

难道 RawConfigParser.has_option(section, option) 不是可以解决这个问题吗?

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())
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']

撰写回答