您的位置:首页 > 其它

difflib模块详解

2021-12-20 12:48 417 查看

 

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)))
对比程序

执行结果:

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))
上面的程序
[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

 

 对比结果如下:

 

 

 

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: