python自动化运维笔记(3)-difflib模块实现文件内容差异对比

Python2.3以上的版本自带difflib模块,无需安装

示例:两个字符串的差异对比

"""
两个字符串的差异对比
"""
import difflib

text1="""text1:
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:
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)))

运行结果:

[root@foundation8 autopy]# /usr/local/python3.6/bin/python3.6 difflib-1.py 
- text1:
?     ^

+ text2:
?     ^

- This module provides classes and functions for comparing sequences.
?                                                ^

+ This module provides classes and functions for Comparing sequences.
?                                                ^

  including HTML and context and unified diffs.
- difflib document v7.4
?                     ^

+ difflib document v7.5
?                     ^

- add string

'-'  包含在第一个序列行中,但不包含在第二个序列行中

'+'  包含在第二个序列行中,但不包含在第一个序列行中

''   两个序列行一致

'?'  标志两个序列行存在增量差异

'^'  两个序列行存在差异的字符

对比结果生成HTML文档

刚才对比生成的结果不是很美观,所以接下来我们将生成HTML文档的格式,然后在浏览器中进行查看

"""
两个字符串的差异对比
生成HTML文档的格式
"""
import difflib

text1="""text1:
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:
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.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))

运行:

[root@foundation8 autopy]# /usr/local/python3.6/bin/python3.6 difflib-HTML.py > /var/www/html/diff.html

浏览器查看:

对比Nginx配置文件差异

   当我们维护多个Nginx配置时,时常会对比不同版本配置文件的差异,使运维人员更加直观地了解不同版本的区别。具体实现思路是读取两个需对比的配置文件,再以换行符作为分隔符,调用difflib.HtmlDiff()生成HTML格式的差异文档。代码如下:

import difflib
import sys

textfile1 = sys.argv[1]
textfile2 = sys.argv[2]

def readfile(filename):
    fileHandle = open (filename,'r')
    text = fileHandle.read().splitlines()
    fileHandle.close()
    return text

text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)

d = difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))
~                                                

运行:

[root@foundation8 autopy]# /usr/local/python3.6/bin/python3.6 difflib_nginx.py nginx.conf.v1.10.1 nginx.conf.v1.15.7 > /var/www/html/diff.html

浏览器查看:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值