我正在阅读YAML文件。如果出现导致异常的语法错误,我会将异常发送给记录器。有什么方法可以在我的日志消息中识别YAML文件的哪一行包含语法错误?
try:
with open(input_path, "r") as yaml_file:
yaml_dict = yaml.load(yaml_file)
except FileNotFoundError:
logger.error("YAML file {} does not exist".format(input_path), exc_info=True)
sys.exit(1)
except:
logger.critical("Error in reading or parsing YAML file {}".format(input_path), exc_info=True)
sys.exit(1)
答案 0 :(得分:2)
查看PyYAMLDocumentation,查找YAMLError()
:
try:
yaml.load("unbalanced blackets: ][")
except yaml.YAMLError, exc:
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
print "Error position: (%s:%s)" % (mark.line+1, mark.column+1)
Error position: (1:22)