2015-08-30 111 views
1

我需要在python中編寫一個模塊,該模塊獲取unix diff -u命令的輸出以及用於創建該輸出並返回輸出第二個文件的文件之一。反向diff -u在python中

-u返回一個差異文件統一格式

任何人都可以向我解釋,真正鋤瞭解,統一格式的差異?

+0

你可以看到[點擊這裏](http://www.gnu.org/software/diffutils/manual/html_node/Unified-Format.html#Unified-Format)也有一個例子,從GNU文檔 –

+0

你不能使用'patch'命令是因爲...? – tripleee

+0

因爲這是一個練習,我需要自己做 –

回答

0

有谷歌的diff-match-patch庫的python port

與PIP安裝它:

pip install diff-match-patch 

從Python解釋器將補丁應用的一個例子:

>>> from diff_match_patch import diff_match_patch 
>>> old_version = '''# 
... # Mac OS X Notice 
... # 
... # This file is not used by the host name and address resolution 
... # or the DNS query routing mechanisms used by most processes on 
... # this Mac OS X system. 
... # 
... # This file is automatically generated. 
... # 
... nameserver 192.168.1.1 
... nameserver 8.8.8.8''' 
>>> patch='''@@ -8,4 +8,4 @@ 
... # This file is automatically generated. 
... # 
... nameserver 192.168.1.1 
... -nameserver 8.8.8.8 
... +nameserver 8.8.4.4''' 
>>> patchobj = diff_match_patch() 
>>> patches = patchobj.patch_fromText(patch) 
>>> patched_version, results = patchobj.patch_apply(patches, old_version) 
>>> print str(patched_version) 
# 
# Mac OS X Notice 
# 
# This file is not used by the host name and address resolution 
# or the DNS query routing mechanisms used by most processes on 
# this Mac OS X system. 
# 
# This file is automatically generated. 
# 
nameserver 192.168.1.1 
nameserver 8.8.4.4 
+0

這不完全是補丁,我在做。我需要獲取diff文件並提取另一個。此代碼是否可以同時工作? –

+0

我想我沒有很好的理解你想完成什麼。由於解釋不夠,你將不得不張貼你正在尋找的確切例子。 –

+0

我明白了。基本上來說:我們用diff -u file_a和file_b創建一個diff文件。然後,我們給程序diff文件,以及文件a或b中的任一個,並且返回另一個作爲輸出 –