首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ConfigObj选项验证

ConfigObj选项验证
EN

Stack Overflow用户
提问于 2013-01-16 04:02:40
回答 1查看 2.9K关注 0票数 1

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

代码语言:javascript
复制
output_mode = option("Verbose", "Terse", "Silent")

我想让我的代码知道用户何时输入了简历中没有的选项。根据我的喜好,Validator似乎只说明了哪个配置键没有通过验证,而没有说明失败的原因:

代码语言:javascript
复制
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)

该代码片段可以工作,但有许多原因导致键可能未通过验证,从不在整数范围内到不在CV中。我不希望必须询问键名,并根据该键的失败情况引发不同类型的异常。是否有更清晰的方法来处理特定类型的验证错误?

Long time stackoverflow阅读器,首次发帖:-)

EN

回答 1

Stack Overflow用户

发布于 2013-01-17 08:50:01

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

代码语言:javascript
复制
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(“Option1”,“Option2”)形式的字符串,而不是列表,所以为了让它看起来更漂亮,你需要抓取()中的子字符串。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14345879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档