gpt4 book ai didi

python - ConfigObj 选项验证

转载 作者:太空宇宙 更新时间:2023-11-03 19:07:23 27 4
gpt4 key购买 nike

我正在使用 ConfigObj 和 Validator 来解析 python 中的配置文件。虽然我非常喜欢这个工具,但我在使用 configSpec 文件进行验证时遇到了问题。我使用 option() configSpec 类型强制从受控词汇表中选择值:

output_mode = option("Verbose", "Terse", "Silent")

我希望我的代码知道用户何时输入简历中没有的选项。根据我的喜好,验证器似乎只说明哪个配置键验证失败,但不说明失败的原因:

from configobj import ConfigObj, flatten_errors
from validate import Validator

config = ConfigObj('config.ini', configspec='configspec.ini')
validator = Validator()
results = config.validate(validator)

if results != True:
for (section_list, key, _) in flatten_errors(config, results):
if key is not None:
print 'The "%s" key in the section "%s" failed validation' % (key, ', '.join(section_list))
else:
print 'The following section was missing:%s ' % ', '.join(section_list)

该代码片段有效,但 key 验证失败的原因有很多,从不在整数范围内到不在 CV 中。我不想询问 key 名称并根据该 key 的失败情况引发不同类型的异常。是否有更简洁的方法来处理特定类型的验证错误?

长期 stackoverflow 读者,第一次发帖:-)

最佳答案

更新:我认为这就是我想做的。关键是 config obj 将错误存储为异常,然后可以根据 ValidateError 子类的错误进行检查。然后,您只需对每个子类进行一次检查,而不是对每个参数值进行一次检查。如果验证失败时验证只是抛出异常可能会更好,但也许您会失去其他功能。

self.config = configobj.ConfigObj(configFile, configspec=self.getConfigSpecFile())
validator = Validator()
results = self.config.validate(validator, preserve_errors=True)

for entry in flatten_errors(self.config, results):

[sectionList, key, error] = entry
if error == False:
msg = "The parameter %s was not in the config file\n" % key
msg += "Please check to make sure this parameter is present and there are no mis-spellings."
raise ConfigException(msg)

if key is not None:
if isinstance(error, VdtValueError):
optionString = self.config.configspec[key]
msg = "The parameter %s was set to %s which is not one of the allowed values\n" % (key, self.config[key])
msg += "Please set the value to be in %s" % optionString
raise ConfigException(msg)

OptionString 只是一个形式为 option("option 1", "option 2") 的字符串,而不是一个列表,因此为了让它看起来不错,您需要获取 () 中的子字符串。

关于python - ConfigObj 选项验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14345879/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com