I'm reading in a YAML file. If there's a syntax mistake that causes an exception, I send the exception to a logger. What is a way to identify in my logging message which line of the YAML file contains the syntax error?
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)
Have a look at the PyYAMLDocumentation, look for 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With