import os,difflib,datetime
import re
def diff(file1,file2):
if not os.path.exists(file1) or not os.path.exists(file2):
print("{} 或者 {} 文件不存在".format(file1,file2))
return -1,"文件不存在"
try:
content1=open(file1,'r',encoding='utf-8').readlines()
content2=open(file2,'r',encoding='utf-8').readlines()
d=difflib.HtmlDiff()
result = d.make_file(content1,content2,context=True)
regex = re.compile("(<table[\s\S]*</table>)[\s]*<table class=\"diff\" summary=\"Legends\">")
table = regex.findall(result)[0]
regex2 = re.compile("<style[\s\S]*</style>")
style = regex2.findall(result)[0]
regex3 = re.compile("<table class=\"diff\" summary=\"Legends\">[\S\s]*</table>")
legend = regex3.findall(result)[0]
if 'No Differences Found' in result:
return 0,"相等"
return 1,[result,table,style,legend]
except Exception as e:
print("{} 与 {} 比较异常 {}".format(file1, file2,e))
return -1,"比较异常"
def dispose(datapath):
files=os.listdir(datapath)
style = ""
legend = ""
tables=[]
is_first=True
for lf in files:
if not os.path.exists("right/"+lf):
print("未发现right中存在同名文件:{}".format(lf))
continue
print("比较left/{} 与 right/{}".format(lf,lf))
ret,result=diff('left/'+lf,'right/'+lf)
if ret==0:
print("{} 无变化".format(lf))
continue
elif ret==-1:
print("{} 比较异常".format(lf))
continue
if is_first:
style=result[2]
legend=result[3]
is_first=False
print("保存比较 {}".format(lf+"_compare.html"))
tables.append({"name":lf,"body":result[1]})
save=open("report/"+lf+"_compare.html","w")
save.writelines(result[0])
save.close()
if not tables:
print("无新变化,无报告")
return
print("生成报告")
html=style
html+="<body><p><h1 style='text-align:center;background-color:#528BFC;padding:6px;border-bottom:1px solid #333;margin-bottom:8px;'><strong>对比报告</strong></h1></p>"
for table in tables:
html+="<p><h2 style='text-align:center;background-color:#D0E1FF;padding:6px;border-bottom:1px solid #333;'><strong>{}</strong></h2></p>".format(table["name"])
html+=table["body"]
html += legend
html+="</body>"
today = datetime.datetime.now().strftime("%Y-%m-%d")
report=open("report/"+today+".html","w")
report.writelines(html)
report.close()
#进入主程序
if __name__=="__main__":
print("开始分析目录 left - right")
if not os.path.exists("left") or not os.path.exists("right"):
print("不存在left文件夹与right文件夹,请自行创建")
exit(0)
dispose('left')