作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想优雅地通知用户他们搞砸的 YAML 文件的确切位置。 python-3.4.1/lib/python-3.4/yaml/scanner.py
的第288行报告了一个常见的解析错误,并通过抛出异常进行处理:
raise ScannerError("while scanning a simple key", key.mark,
"could not found expected ':'", self.get_mark())
我正在纠结如何举报。
try:
parsed_yaml = yaml.safe_load(txt)
except yaml.YAMLError as exc:
print ("scanner error 1")
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
print("Error parsing Yaml file at line %s, column %s." %
(mark.line, mark.column+1))
else:
print ("Something went wrong while parsing yaml file")
return
这给出了
$ yaml_parse.py
scanner error 1
Error parsing Yaml file line 1508, column 9.
但是我如何获取错误文本以及 key.mark
和其他标记中的内容?
更有用的是,我如何检查 PyYaml 源代码来解决这个问题? ScannerError 类似乎忽略了参数(来自 scanner.py
第 32 行):
class ScannerError(MarkedYAMLError):
pass
最佳答案
根据@Anthon 的回答,这段代码运行良好:
try:
import yaml
except:
print ('Fatal error: Yaml library not available')
quit()
f = open ('y.yml')
txt = f.read()
try:
yml = yaml.load(txt, yaml.SafeLoader)
except yaml.YAMLError as exc:
print ("Error while parsing YAML file:")
if hasattr(exc, 'problem_mark'):
if exc.context != None:
print (' parser says\n' + str(exc.problem_mark) + '\n ' +
str(exc.problem) + ' ' + str(exc.context) +
'\nPlease correct data and retry.')
else:
print (' parser says\n' + str(exc.problem_mark) + '\n ' +
str(exc.problem) + '\nPlease correct data and retry.')
else:
print ("Something went wrong while parsing yaml file")
return
# make use of `yml`
带有轻微破坏数据的示例输出:
$ yaml_parse.py
Error while parsing YAML file:
parser says
in "<unicode string>", line 1525, column 9:
- name: Curve 1
^
could not found expected ':' while scanning a simple key
Please correct data and retry.
$ yaml_parse.py
Error while parsing YAML file:
parser says
in "<unicode string>", line 1526, column 10:
curve: title 1
^
mapping values are not allowed here
Please correct data and retry.
关于python - 如何从 PyYAML 异常中获取详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30269723/
我是一名优秀的程序员,十分优秀!