简体   繁体   中英

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!

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM