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

 

 對比結果如下:

 

 

 

參考書籍:自動化運維技術與最佳實踐  劉天斯

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM