二、实战:文件内容差异对比方法

一、项目介绍

本次介绍如果通过difflib模块实现文件内容差异对比。difflib作为Python的标准库模块,无需安装,作用是对比文件之间的差异,且支持输出可读性比价强的HTML文档,与Linux下的diff命令相似。我们可以使用difflib对比代码,配置文件的差别,在版本控制方面是非常有用的。

二、案例

本案例通过使用difflib模块实现两个字符串的差异对比,然后以版本控制风格进行输出

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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_line = text1.splitlines()   # 以行进行分割,以便进行对比
text2 = """text2
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
"""
text2_line = text2.splitlines()   # 以行进行分割,以便进行对比
d = difflib.Differ()   # 创建Differ()对象
diff = d.compare(text1_line,text2_line)  # 采用compare方法字符串进行比较
print('\n'.join(list(diff)))

运行:

ps:此示例采用Differ()类对两个字符串进行比较,另外difflib的SequenceMatcher()类支持任意类型序列的比较,HtmlDiff()类支持将比较结果输出为HTML格式;

符合的意义:

  • '_' 包含在第一个序列行中,但不包含在第二个序列行
  • '+' 包含在第二个序列行中,但不包含在第一个序列行
  • '' 两个序列行一致
  • '?' 标志两个序列行存在增量差异
  • '^' 标志出两个序列行存在的差异字符

三、生成美观的对比HTML格式文档

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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_line = text1.splitlines()   # 以行进行分割,以便进行对比
text2 = """text2
This module provides classes and functions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
"""
text2_line = text2.splitlines()   # 以行进行分割,以便进行对比
# d = difflib.Differ()   # 创建Differ()对象
# diff = d.compare(text1_line,text2_line)  # 采用compare方法字符串进行比较
# print('\n'.join(list(diff)))

d = difflib.HtmlDiff()
print(d.make_file(text1_line,text2_line))

四、对比Nginx配置文件差异

当我们维护多个Nginx配置时,是常会对比不同版本配置文件的差异,使运维人员更加清晰地了解不同版本迭代后的更新项,实现的思路是读取两个需对比的配置文件,再以换行符作为分隔符,调用difflib.HtmlDiff()生成HTML格式的差异文件。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import difflib
import sys

try:
    text_file1 = sys.argv[1]   # 第一个配置文件路径参数
    text_file2 = sys.argv[2]   # 第二个配置文件路径参数
except Exception as e:
    print("Error:" + str(e))
    print("Usage: simple3.py filename1 filename2")
    sys.exit()

def readfile(filename):  # 文件读取分隔函数
    try:
        file_Handle = open(filename,'rb')
        text = file_Handle.read().splitlines()   # 读取后一行分隔
        file_Handle.close()
        return text
    except IOError as error:
        print("Read file Error:" + str(error))
        sys.exit()
if text_file1 == "" or text_file2=="":
    print("Usage filename1 filename2" )
    sys.exit()

text1_lines = readfile(text_file1)   # 调用readfile函数,获取分隔后的字符串
text2_lines = readfile(text_file2)
d = difflib.HtmlDiff()   # 创建htmlDiff()类对象
print(d.make_file(text_file1,text_file2))  # 通过make_file方法输出HTML格式的比对结果

posted @ 2018-06-03 14:30  云原生运维社区  阅读(750)  评论(0编辑  收藏  举报