简体   繁体   中英

Reverse diff -u in python

I need to write a module in python that gets the output of a unix diff -u command and one of the files that were used to create that ouput and in return output the second file.

The diff -u returns a diff file in a unified format

Could anyone explain to me really hoe to understand that unified format?

There's a python port of Google's diff-match-patch library:

Install it with pip:

pip install diff-match-patch

An example of applying a patch from the python interpreter:

>>> 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM