Python ConfigParser:如何计算特定部分中设置的选项(而不是默认值)
我有一个使用标准 ConfigParser 库中的 RawConfigParser 读取的配置文件。我的配置文件有一个 [DEFAULT] 部分,后面跟着一个 [specific] 部分。当我循环浏览 [特定] 部分中的选项时,它包括 [默认] 下的选项,这就是应该发生的情况。
但是,为了进行报告,我想知道该选项是否已在 [特定] 部分或 [默认] 中设置。有没有办法使用 RawConfigParser 的接口来做到这一点,或者我别无选择,只能手动解析文件? (我找了一下,我开始担心最坏的情况......)
例如
[DEFAULT]
name = a
surname = b
[SECTION]
name =
bage = 23
你怎么知道,使用 RawConfigParser 接口,是否选项名称 &姓氏是从 [DEFAULT] 部分还是 [SECTION] 部分加载?
(我知道 [DEFAULT] 意味着适用于所有人,但您可能想在内部报告类似的事情,以便通过复杂的配置文件工作)
谢谢!
I have a config file that I read using the RawConfigParser in the standard ConfigParser library. My config file has a [DEFAULT] section followed by a [specific] section. When I loop through the options in the [specific] section, it includes the ones under [DEFAULT], which is what is meant to happen.
However, for reporting I wanted to know whether the option had been set in the [specific] section or in [DEFAULT]. Is there any way of doing that with the interface of RawConfigParser, or do I have no option but to parse the file manually? (I have looked for a bit and I'm starting to fear the worst ...)
For example
[DEFAULT]
name = a
surname = b
[SECTION]
name = b
age = 23
How do you know, using RawConfigParser interface, whether options name & surname are loaded from section [DEFAULT] or section [SECTION]?
(I know that [DEFAULT] is meant to apply to all, but you may want to report things like this internally in order to work your way through complex config files)
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我最近通过将选项放入字典中,然后合并字典来做到这一点。它的巧妙之处在于用户参数会覆盖默认值,并且很容易将它们全部传递给函数。
I did this recently by making the options into dictionaries, and then merging the dictionaries. The neat thing about it is that the user parameters override the defaults, and it's easy to pass them all to a function.
给定此配置文件:
这是一个可以理解第 1 部分使用默认姓氏属性的程序。
这是输出:
Given this configuration file:
Here's a program that can understand that Section 1 is using the default surname property.
And here's the output:
RawConfigParser.has_option(section, option)
不可以完成这项工作吗?Doesn't
RawConfigParser.has_option(section, option)
do the job?