1.difflib介绍
difflib作为 Python的标准库模块,无需安装,作用是对比文本之间的差异,且支持 输出可读性比较强的HTML文档,与Linux下的diff命令相似。我们可以 使用difflib对比代码、配置文件的差别,在版本控制方面是非常有用。 Python 2.3或更高版本默认自带difflib模块,无需额外安装。
示例1:两个字符串的差异对比
[yhl@myhost part2]$ cat simple1.py
#
!/usr/bin/python
#
_*_coding:utf-8_*_
#
****************************************************************#
#
ScriptName: simple1.py
#
Author: BenjaminYang
#
Create Date: 2019-05-13 11:08
#
Modify Author: BenjaminYang
#
Modify Date: 2019-05-13 11:08
#
Function:
#
***************************************************************#
import
difflib
text1
=
"""
text1: #定义字符串1
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
"""
text1_lines
=text1.splitlines()
#
以行进行分隔
text2=
"""
text2: #定义字符串2
This module provides classes and functions for Comparing sequences.
including HTML and context and unified diffs.
difflib document v7.5
"""
text2_lines
=
text2.splitlines()
d
=difflib.Differ()
#
创建Differ()对象
diff=d.compare(text1_lines,text2_lines)
#
采用compare方法对字符串进行比较
print
'
\n
'
.join(list(diff))
本示例采用Differ()类对两个字符串进行比较,另外difflib的 SequenceMatcher()类支持任意类型序列的比较,HtmlDiff()类支持 将比较结果输出为HTML格式
示例运行结果
符号含义说明
生成美观的对比HTML格式文档
采用HtmlDiff()类将新文件命名为simple2.py,运行# python simple2.py>diff.html,再 使用浏览器打开diff.html文件,结果如图示2-2所示,HTML文档包括了 行号、差异标志、图例等信息,可读性增强了许多的make_file()方法就可以生成美观的HTML 文档,对示例1中代码按以下进行修改:
示例2:对比Nginx配置文件差异
当我们维护多个Nginx配置时,时常会对比不同版本配置文件的差 异,使运维人员更加清晰地了解不同版本迭代后的更新项,实现的思路 是读取两个需对比的配置文件,再以换行符作为分隔符,调用 difflib.HtmlDiff()生成HTML格式的差异文档。实现代码如下:
【/home/test/difflib/simple3.py】
#
!/usr/bin/python
#
_*_coding:utf-8_*_
#
****************************************************************#
#
ScriptName: simple3.py
#
Author: BenjaminYang
#
Create Date: 2019-05-13 12:32
#
Modify Author: BenjaminYang
#
Modify Date: 2019-05-13 12:32
#
Function:
#
***************************************************************#
import
difflib
import
sys
try
:
textfile1
=sys.argv[1]
#
第一个配置文件路径参数
textfile2=sys.argv[2]
#
第二个配置文件路径参数
except
Exception, e:
print
"
Error:
"
+
str(e)
print
"
Usage: simple3.py filename1 filename2
"
sys.exit()
def
readfile(filename):
#
文件读取分隔函数
try
:
fileHandle
=open(filename,
'
rb
'
)
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: simple3.py filename1 filename2
"
sys.exit()
text1_lines
=
readfile(textfile1)
text2_lines
=
readfile(textfile2)
d
=difflib.HtmlDiff()
#
创建HtmlDiff()对象
print
d.make_file(text1_lines,text2_lines)
#
通过make_file的方法生成HTML文件的对比结果
[yhl@myhost part2]$ python simple3.py /home/yhl/devpython/part2/nginx.conf.v1 /home/yhl/devpython/part2/nginx.conf.v2 >diff.html
nginx.conf.v1与nginx.conf.v2配置文件对比结果

