gpt4 book ai didi

python - 如何从 PyYAML 异常中获取详细信息?

转载 作者:太空狗 更新时间:2023-10-30 02:19:23 36 4
gpt4 key购买 nike

我想优雅地通知用户他们搞砸的 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/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com