Python自帶difflib模組
阿新 • • 發佈:2020-11-04
官方文件:https://docs.python.org/3/library/difflib.html
difflib模組的作用是比對文字之間的差異,且支援輸出可讀性比較強的HTML文件,與Linux下的vimdiff命令相似。
vimdiff效果如下:
在介面測試時,常常需要對不同版本的同一個介面的response進行比對,來驗證新版本的功能可靠性。介面數量多,加之vimdiff命令輸出的結果讀起來不是很友好,這時python自帶的difflib模組就可以發揮作用了。
difflib.Differ類
import difflib
text1 = ''' yi hang
er hang
'''.splitlines(keepends=True)
text2 = ''' yi hang
er han
san hang
'''.splitlines(keepends=True)
d = difflib.Differ() # 建立Differ 物件
result = list(d.compare(text1, text2))
result = "".join(result)
print(result)
結果:
註釋:
difflib.
HtmlDiff
類
import difflib
import sys
import argparse
# 讀取要比較的檔案
def read_file(file_name):
try:
file_desc = open(file_name, 'r')
# 讀取後按行分割
text = file_desc.read().splitlines()
file_desc.close()
return text
except IOError as error:
print('Read input file Error: {0}'.format(error))
sys.exit()
# 比較兩個檔案並把結果生成一個html檔案
def compare_file(file_1, file_2):
if file_1 == "" or file_2 == "":
print('檔案路徑不能為空:第一個檔案的路徑:{0}, 第二個檔案的路徑:{1} .'.format(file_1, file_2))
sys.exit()
else:
print("正在比較檔案{0} 和 {1}".format(file_1, file_2))
text1_lines = read_file(file_1)
text2_lines = read_file(file_2)
diff = difflib.HtmlDiff() # 建立HtmlDiff 物件
result = diff.make_file(text1_lines, text2_lines) # 通過make_file 方法輸出 html 格式的對比結果
# 將結果寫入到result_compare.html檔案中
try:
with open('result_compare.html', 'w') as result_file:
result_file.write(result)
print("比較完成")
except IOError as error:
print('寫入html檔案錯誤:{0}'.format(error))
if __name__ == "__main__":
# To define two arguments should be passed in, and usage: -f1 f_name1 -f2 f_name2
my_parser = argparse.ArgumentParser(description="傳入兩個檔案引數")
my_parser.add_argument('-f1', action='store', dest='f_name1', required=True)
my_parser.add_argument('-f2', action='store', dest='f_name2', required=True)
# retrieve all input arguments
given_args = my_parser.parse_args()
file1 = given_args.f_name1
file2 = given_args.f_name2
compare_file(file1, file2)
result_compare.html效果:
注意:當介面response返回的行數很多,difflib可能會發生比對錯行,導致比對結果不準確,不妨去試一試xmldiff和json-diff