繁体   English   中英

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

[英]Python ConfigParser: how to work out options set in a specific section (rather than defaults)

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

但是,对于报告,我想知道是在[特定]部分还是[默认]中设置了该选项。 是否可以通过RawConfigParser的接口来执行此操作,或者我只能手动解析文件,所以别无选择吗? (我已经寻找了一点,我开始担心最糟糕的事情...)

例如

[默认]

名称= a

姓= b

[部分]

名称= b

年龄= 23

您如何使用RawConfigParser界面从[DEFAULT]部分或[SECTION]部分中加载选项名称和姓氏?

(我知道[DEFAULT]适用于所有对象,但您可能希望在内部报告类似的内容,以便通过复杂的配置文件进行操作)

谢谢!

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

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

给定此配置文件:

[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)完成这项工作吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM