捕获yaml解析错误

时间:2016-06-24 08:25:31

标签: python-3.x exception pyyaml

我似乎无法让我的代码发现错误:

我有一个包含数千个条目的yaml文件,一些条目被修复,生成

"expected <block end>, but found %r" % token.id, token.start_mark)
yaml.parser.ParserError: while parsing a block mapping

我正在使用Pyyaml和python3

with open('yamlfile') as yf:
    allyml = yaml.load_all(yf)
    for listing in allyml:
        try:
            <do stuff>
        #except yaml.parser.ParserError:
        except:
            continue 

捕获ParserError不起作用,也不起作用。

它可以正常工作,直到它到达受损的yaml条目。

由于PYyaml抛出一个ParserError,它必须是我的try语句......

1 个答案:

答案 0 :(得分:-1)

执行:

with open('yamlfile') as yf:
    allyml = yaml.load_all(yf)
    for listing in allyml:
        try:
            <do stuff>
        # Catch all YAMLErrors
        except yaml.YAMLError, exc:
           # print line number of error
           if hasattr(exc, 'problem_mark'):
              mark = exc.problem_mark
              print "Error position: (%s:%s)" % (mark.line+1, mark.column+1)
           continue 

而不是:

with open('yamlfile') as yf:
    allyml = yaml.load_all(yf)
    for listing in allyml:
        try:
            <do stuff>
        #except yaml.parser.ParserError:
        except:
            continue 

这将允许您捕获所有YAML错误并显示错误的确切行号和列。