Pythonでdiff
30分プログラム、その252。Pythonでdiffを作ってみる。
diffをちゃんと作ると大変そうだけど、Pythonのdifflibを使えば簡単にできる。
>>> import >>> a = file('foo').readlines() >>> b = file('bar').readlines() >>> difflib.unified_diff(a,b)
とするだけで、diffがとれちゃう。便利、便利。
使い方
$ python diff.py ~/tmp/foo ~/tmp/bar --- /Users/mzp/tmp/foo Sat Feb 23 21:51:47 2008 +++ /Users/mzp/tmp/bar Sat Feb 23 21:51:53 2008 @@ -1,3 +1,3 @@ foo -bar +BAR baz
ソースコード
#! /usr/bin/python # -*- mode:python; coding:utf-8 -*- # # diff.py - # # Copyright(C) 2008 by mzp # Author: MIZUNO Hiroki / mzpppp at gmail dot com # http://howdyworld.org # # Timestamp: 2008/02/23 21:44:14 # # This program is free software; you can redistribute it and/or # modify it under MIT Lincence. # from sys import argv,stdout from difflib import unified_diff from pprint import pprint import time import os def mtime(path): return os.stat(path)[8] def info(path): content = file(path).readlines() mtime = time.ctime(os.stat(path)[8]) return (content,mtime) pathA,pathB = argv[1:] (fileA,mtimeA) = info(pathA) (fileB,mtimeB) = info(pathB) stdout.writelines(unified_diff(fileA,fileB, pathA,pathB, mtimeA,mtimeB))