我試圖創建一個腳本,您可以在其中導入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