#!/usr/bin/env python
# coding=utf-8
import sys
import difflib
try:
file1 = sys.argv[1]
file2 = sys.argv[2]
except Exception, e:
print "Error: " + str(e)
print "Uasge: diff.py file1 file2"
sys.exit()
#读取文件内容的函数
def readfile(filename):
try:
content = open(filename, 'rb')
text = content.read().splitlines()
content.close()
return text
except IOError as error:
print 'Read file Error: ' + str(error)
sys.exit()
if file1 == "" or file2 == "":
print "Uasge: diff.py file1 file2"
sys.exit()
text1_lines = readfile(file1)
text2_lines = readfile(file2)
#实例化 difflib 模块的 HtmlDiff 类来生成对比结果的 HTML 文件
d = difflib.HtmlDiff()
print d.make_file(text1_lines, text2_lines)
test1 的内容
test1
diff
test2 的内容
test2
diFF
aaa
执行脚本
python diff.py test1 test2 > test.html
具体效果: