返回总目录页

difflib模块详解

 

1、两个字符串对比

import difflib
text1=""" test1 #定义字符串
hellow
my name is machanwei!
difflib document v7.4
add str
"""
text1_lines=text1.splitlines() #以行进行分隔,以便进行对比
text2="""text2:   #定义字符串2
hellow
my name is machangwei!
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)))
对比程序

执行结果:

 

 - + 好像分别代表不同的文本,来区分文本用。这里-是1的,+是文本2的。?是有区别的地方,有区别的地方会标记箭头,只有-没有+,也就是不是成对出现应该是只有某一方有文本

 

2、对比文件生成html文档

执行生成html语句

(venv) D:\python_mcw>python python自动化运维书\difflib模块学习.py >>..\diffres.html

 

 

 挺好对比的

import difflib
text1=""" test1 #定义字符串
hellow
my name is machanwei!
difflib document v7.4
add str
"""
text1_lines=text1.splitlines() #以行进行分隔,以便进行对比
text2="""text2:   #定义字符串2
hellow
my name is machangwei!
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)))

#替换成下面这些:
d=difflib.HtmlDiff()
print(d.make_file(text1_lines,text2_lines))
上面的程序

3、对比文件差异

[root@hecs-358404 ~]# cat mcw.py 
# __*__ coding:utf-8 _*_
#!/usr/bin/env python
import difflib
import sys

try:
    mcwfile1=sys.argv[1]  #第一个配置文件路径参数
    mcwfile2=sys.argv[2] #第二个配置文件路径参数
except Exception as e:
    print("Error:"+str(e))
    print("Usage: mcw.py  mcwfile1 mcwfile2")
    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 mcwfile1=="" or mcwfile2=="":
    print("Usage: mcw.py  mcwfile1 mcwfile2")
    sys.exit()
text1_lines=readfile(mcwfile1) #调用函数,获取分隔后的字符串
text2_lines=readfile(mcwfile2)
d=difflib.HtmlDiff()
print d.make_file(text1_lines,text2_lines)
对比程序
server {

       listen       80;

       server_name  blog.etiantian.org;

       location / {

                root   html/blog;

                index  index.html index.htm;

          }

        location ~* .*\.(php|php5)?$ {

          root html/blog;

              fastcgi_pass  127.0.0.1:9000;

              fastcgi_index index.php;

              include fastcgi.conf;

          }

}
文件1
#server {

       listen       80;

            server_name  blog.etiantian.org;

       location / {

                root   html/blog;

                index  index.html index.htm;

          }

        machangwei
        location ~* .*\.(php|php5)?$ {

          root html/blog;

              fastcgi_pass  127.0.0.1:9000;

              fastcgi_index index.php;

              include fastcgi.conf;

          }
        fffffff
}
文件2

 

 对比结果如下:

 

 

 

参考书籍:自动化运维技术与最佳实践  刘天斯

 

posted @ 2021-12-20 12:48  马昌伟  阅读(726)  评论(0编辑  收藏  举报
博主链接地址:https://www.cnblogs.com/machangwei-8/