简体   繁体   English

ConfigObj:防止写入空部分

[英]ConfigObj: prevent writing empty sections

I'm using ConfigObj (5.0.6, both on python 2.7 and python 3.8) to manage my configs, but when I'm writing to file config with some sections only presented in configspec, they're appearing only as empty sections, which is not desired.我正在使用 ConfigObj(5.0.6,在 python 2.7 和 python 3.8 上)来管理我的配置,但是当我使用仅在 configspec 中提供的某些部分写入文件配置时,它们仅显示为空部分,其中是不想要的。 I would appreciate any suggestions of fixing that behaviour of ConfigObj.我将不胜感激任何修复 ConfigObj 行为的建议。

Minimal example of what happening:发生的事情的最小例子:

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

Output:输出:

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

Desired output (there should be no empty sections when writing):所需的输出(写入时不应有空白部分):

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

Edit 1: I'm using write() to actually write into file so I would prefer not just mess with returned list of strings编辑 1:我使用 write() 来实际写入文件,所以我不希望只是弄乱返回的字符串列表

To put default values in the output config file, pass copy = True to the validate:要将默认值放在输出配置文件中,请将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())

which gives your desired output这给出了你想要的输出

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

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

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