python - ConfigObj 选项验证

标签 python exception configobj

我正在使用 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/

相关文章:

java.io.StreamCorruptedException : invalid stream header: FAD08000

java - 在哪里处理致命异常

python - ConfigObj 'un-nest' 部分

python - python configObj可以处理没有 '='的行吗

python - 为什么字符串乘以负整数会得到空字符串?

python - 使用 python 从 xml 填充列表

python - 在没有 if 条件的情况下打印数据文件中的所有行

python - 使用相同种子的不同 Pytorch 随机初始化

language-agnostic - 何时/为何使用自定义异常

python - 有什么办法可以在 python 中使用 configobj 编写注释