Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyYAML find line of incorrect YAML syntax error

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)
like image 906
forest Avatar asked Nov 17 '17 22:11

forest


1 Answers

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)
like image 185
tinita Avatar answered Oct 24 '22 21:10

tinita