我使用ConfigObj和验证器来解析Python语言中的配置文件。虽然我非常喜欢这个工具,但我在使用configSpec文件进行验证时遇到了问题。我使用了option() configSpec类型,它强制从受控词汇表中选择值:
output_mode = option("Verbose", "Terse", "Silent")我想让我的代码知道用户何时输入了简历中没有的选项。根据我的喜好,Validator似乎只说明了哪个配置键没有通过验证,而没有说明失败的原因:
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阅读器,首次发帖:-)
发布于 2013-01-17 08:50:01
更新:我认为这就是我想要做的。关键是配置obj将错误存储为异常,然后可以根据ValidateError子类检查这些异常。然后,您只需对每个子类执行一次检查,而不是对每个参数值执行一次检查。如果validation只是在验证失败时抛出一个异常,那可能会更好,但可能会失去其他功能。
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”)形式的字符串,而不是列表,所以为了让它看起来更漂亮,你需要抓取()中的子字符串。
https://stackoverflow.com/questions/14345879
复制相似问题