python---difflib


文件內容差異對比

difflib為python的標准庫模塊,無需安裝。作用時對比文本之間的差異。並且支持輸出可讀性比較強的HTML文檔,與LInux下的diff 命令相似。在版本控制方面非常有用。

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

import difflib
text1 = """ #定義字符串1
user www www;
worker_processes 2;

error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

pid logs/nginx.pid;


events {
use epoll;
worker_connections 2048;
}


http {
include mime.types;
default_type application/octet-stream;

server {
listen 80;
server_name itoatest.example.com;
root /apps/oaapp;

charset utf-8;
access_log logs/host.access.log main;

"""
text1_lines = text1.splitlines() #以行進行分割

text2 = """ #定義字符串2
user www www;
worker_processes 2;

error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

pid logs/nginx.pid;


events {
use epoll;
worker_connections 2000;
}


http {
include mime.types;
default_type application/octet-stream;

server {
listen 80;
server_name itoatest.example.com;
root /apps/oaapp;

charset utf-8;
access_log logs/host.access.log main;

"""
text2_lines = text2.splitlines()

d = difflib.Differ()#創建Differ對象
diff = d.compare(text1_lines,text2_lines)
print('\n'.join(list(diff)))
符號 含義
'-' 包含在第一個系列行中,但不包含第二個。
'+' 包含在第二個系列行中,但不包含第一個。
' ' 兩個系列行一致
'?' 存在增量差異
'^' 存在差異字符

 

 

 

 

 

 

生成對比HTML格式 文檔

  使用HtmlDiff()類的make_file()方法生成HTML文檔

#對上面代碼修改

# d = difflib.Differ()#創建Differ對象
# diff = d.compare(text1_lines,text2_lines)
# print('\n'.join(list(diff)))



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

 python xxx.py > diff.html

對比Nginx配置文件差異腳本

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#Author: guhf

import difflib
import string
import sys

try:
    textfile1 = sys.argv[1]
    textfile2 = sys.argv[2]
except Exception:
    print("Error:" + str(e))
    print("Usage: xxxx.py filename1 filename2")
    sys.exit()
def readfile(filename):
    try:
        fileHandle = open(filename,'r')
        text = fileHandle.read().splitlines()
        fileHandle.close()
        return text
    except IOError as error:
        print('Read file Error:' + str(error))
        sys.exit()

if textfile1 == "" or textfile2 == "":
    print("Usage:test.py filename1 filename2")
    sys.exit()

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

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

  


免責聲明!

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



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