文件内容差异对比
difflib为python的标准库模块,无需安装。作用时对比文本之间的差异。并且支持输出可读性比较强的HTML文档,与LInux下的diff 命令相似。在版本控制方面非常有用。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: 小祎
import difflib
text1 = """ #定义字符串1
user www www;
worker_processes 2;
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
pid logs/nginx.pid;
events {
use epoll;
worker_connections 2048;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name itoatest.example.com;
root /apps/oaapp;
charset utf-8;
access_log logs/host.access.log main;
"""
text1_lines = text1.splitlines() #以行进行分割
text2 = """ #定义字符串2
user www www;
worker_processes 2;
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
pid logs/nginx.pid;
events {
use epoll;
worker_connections 2000;
}
http {
include mime.types;
default_type application/octet-stream;
server {
listen 80;
server_name itoatest.example.com;
root /apps/oaapp;
charset utf-8;
access_log logs/host.access.log main;
"""
text2_lines = text2.splitlines()
d = difflib.Differ()#创建Differ对象
diff = d.compare(text1_lines,text2_lines)
print('\n'.join(list(diff)))
符号
含义
'-'
包含在第一个系列行中,但不包含第二个。
'+'
包含在第二个系列行中,但不包含第一个。
' '
两个系列行一致
'?'
存在增量差异
'^'
存在差异字符
生成对比HTML格式 文档
使用HtmlDiff()类的make_file()方法生成HTML文档
#对上面代码修改
# d = difflib.Differ()#创建Differ对象
# diff = d.compare(text1_lines,text2_lines)
# print('\n'.join(list(diff)))
d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))
python xxx.py > diff.html
对比Nginx配置文件差异脚本
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#Author: guhf
import difflib
import string
import sys
try:
textfile1 = sys.argv[1]
textfile2 = sys.argv[2]
except Exception:
print("Error:" + str(e))
print("Usage: xxxx.py filename1 filename2")
sys.exit()
def readfile(filename):
try:
fileHandle = open(filename,'r')
text = fileHandle.read().splitlines()
fileHandle.close()
return text
except IOError as error:
print('Read file Error:' + str(error))
sys.exit()
if textfile1 == "" or textfile2 == "":
print("Usage:test.py filename1 filename2")
sys.exit()
text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)
d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))