【问题标题】:Python ConfigParser: how to work out options set in a specific section (rather than defaults)Python ConfigParser:如何计算在特定部分中设置的选项(而不是默认值)
【发布时间】:2010-02-22 13:28:26
【问题描述】:

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

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

例如

[默认]

名字 = 一个

姓氏= b

[部分]

名字 = b

年龄 = 23

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

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

谢谢!

【问题讨论】:

  • 为什么不显示配置文件的示例而不是用文字写出来?
  • 我忘了说我可以从 .defaults() 中获取默认值,因此通过与部分中的选项进行比较,我可以看到哪些选项仅在部分中设置(因为它们不会处于默认状态)。但是,我无法查看哪些是默认值,然后在部分中被覆盖

标签: python configparser


【解决方案1】:

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

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

    【讨论】:

      【解决方案3】:

      RawConfigParser.has_option(section, option) 不做这项工作吗?

      【讨论】:

      • 很遗憾没有,在我的示例中:cfg.has_option('SECTION','surname') 会返回 true,但 surname 实际上是在默认值中定义的,并且只有那里
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-12
      相关资源
      最近更新 更多