Ken
Ken

Reputation: 31

Python when catching exceptions, how I can get the line number?

I know there is another thread on this but it didn't solve my problem, please read my question!

Basically, I'm parsing a YAML file to ensure it has all the correct keys and values I want. If the YAML file has an incorrect value or key that it needs to have, then I want to print a message that says where the incorrect value or key is.

Example:
Let's say for this YAML file:

Groceries:
Apples: Granny
Milk: Skim
Bread: Wheat

Let's say I was expecting 'Whole' as the value for 'Milk'. If that line is line 3, how do I print a message that says "error: invalid value blah blah on LINE 3"??

Thanks so much!

Upvotes: 3

Views: 2544

Answers (2)

Michael Barton
Michael Barton

Reputation: 9556

I had a similar requirement to the question. I couldn't find a python solution but found kwalify - http://www.kuwata-lab.com/kwalify. You can use it as a command line tool. It allows you to specify the keys, and allowable values as a schema. You then validate your YAML file as follows:

kwalify -f schema.yaml document.yaml

Upvotes: 0

Jakob Bowyer
Jakob Bowyer

Reputation: 34698

From the PyYaml documentation

>>> 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)

Upvotes: 5

Related Questions