【问题标题】:ConfigObj: prevent writing empty sectionsConfigObj:防止写空部分
【发布时间】:2020-01-06 16:35:27
【问题描述】:

我正在使用 ConfigObj(5.0.6,在 python 2.7 和 python 3.8 上)来管理我的配置,但是当我写入文件配置时,某些部分仅在 configspec 中显示,它们只显示为空部分,这是不希望的。对于修复 ConfigObj 的行为的任何建议,我将不胜感激。

发生的事情的最小示例:

from configobj import ConfigObj
from validate import Validator

spec = ["[Section]", "option = boolean(default=True)"]

config = ConfigObj(infile={'Section2': {'option2': False}}, configspec=spec)
config.validate(Validator())
print(config)
print(config.write())

输出:

{'Section2': {'option2': False}, 'Section': {'option': True}}
['[Section2]', '    option2 = False', '[Section]']

想要的输出(写的时候不能有空的部分):

{'Section2': {'option2': False}, 'Section': {'option': True}}
['[Section2]', '    option2 = False']

编辑 1:我使用 write() 来实际写入文件,所以我不希望只是弄乱返回的字符串列表

【问题讨论】:

    标签: python config ini configobj


    【解决方案1】:

    要将默认值放入输出配置文件,请将copy = True 传递给验证:

    from configobj import ConfigObj
    from validate import Validator
    
    spec = ["[Section]", "option = boolean(default=True)"]
    
    config = ConfigObj(infile={'Section2': {'option2': False}}, configspec=spec)
    # set copy = True            vvvvvvvvvvv
    config.validate(Validator(), copy = True)
    print(config)
    print(config.write())
    

    它给出了你想要的输出

    {'Section2': {'option2': False}, 'Section': {'option': True}}
    ['[Section2]', 'option2 = False', '[Section]', 'option = True']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 2013-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多