我试图创建一个脚本,您可以在其中导入yaml文件并验证它是否为yaml格式。我也希望它列出文件中的每个错误。我想要做的是利用yaml安全加载,然后当它失败时打印错误消息,忽略该行,然后重新读取文件,并重复直到打印文件中的所有错误。导入文件时是否有一种简单的方法可以忽略行列表?继承人我现在的代码:解析yaml文件时跳过行
#Verify YAML modules is installed
try:
import yaml
except:
print ('You do not have the YAML module installed.\n'+'Run: pip install yaml to fix this')
quit()
#Verify argparse module is installed
try:
import argparse
except:
print ('You do not have the argparse module installed.\n'+'Run: pip install argparse to fix this')
quit()
import itertools
#Loop variable
i = 0
#Configuration for argument parsing
parser = argparse.ArgumentParser()
parser.add_argument("path", help='File/Directory path to be examined', type=str)
args = (parser.parse_args())
#The main loop
while (i == 0):
skip = []
#Loop to skip lines for re-iteration
with open(args.path) as infile:
for line in itertools.islice(infile, skip, None):
#Verify file is in YAML, if so save as dict then end
try:
yml = yaml.load(txt, yaml.SafeLoader)
print yml
i == 1
#if not yaml record error seen, then redo the loop skipping previous errors
except yaml.YAMLError as exc:
print ("Error while parsing YAML file:")
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
print "Error position: (%s:%s)" % (mark.line+1, mark.column+1)
print exc
skip.add(mark.line+1)
我不认为高层次的逻辑是合理的; yaml可以通过从其中删除一行来变得无法解析,因此您最终可能会遇到跳过该行并重新分析该文件的问题,从而无法验证。 – cowbert
嗯,那么还有另一种方法来列出除此之外的文件中的所有yaml错误。我想我可以看到你的话。但让我们说第2行和第78行有问题,用我使用的安全加载方法会显示第2行的错误,然后停止。使用该脚本的用户基本上必须运行该脚本,修复1行,运行脚本,修复另一行,这比一次修复所有错误需要更长的时间(如果我能弄清楚如何一次显示它们) –
@ VincentMorris您可以尝试跳过所有行,直到找到与错误发生前相同的缩进级别并从此处重新启动。这里有一些注意事项:1)你的错误指示器可能指示第1行,但实际的修正是几行前进2)SafeLoader不能加载带有标签的YAML 3)你使用的PyYAML有未修复的错误,在完美的YAML上抛出错误4)PyYAML仍然不支持YAML 1.2规范(从2009年开始)。 – Anthon