2017-11-17 104 views
1

我正在閱讀YAML文件。如果存在導致異常的語法錯誤,我會將異常發送給記錄器。什麼是在我的日誌消息中識別YAML文件的哪一行包含語法錯誤的方法?PyYAML找到不正確的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) 

回答

1

看一看的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)