4

Is there any way to get the following output (especially the 1,4c1,4 syntax) from Python's difflib?

diff foo baz 
1,4c1,4
< 'asdf'
< 'asdf'
< 'asdf'
< 'asdf'
---
> asdf
> asdf
> asdf
> asdf
kev
  • 8,928
  • 14
  • 61
  • 103

2 Answers2

2

There's a good implementation here: https://github.com/glanois/code/blob/master/python/ppt/diff.py

Its header comment says:

This class produces differences in the POSIX default format (see http://www.unix.com/man-page/POSIX/1posix/diff/), which is the same as the Gnu diff "normal format" (see http://www.gnu.org/software/diffutils/manual/diffutils.html#Normal).

I tested it with python 2.7, producing the following output for your example:

$ python diff.py foo baz
1,4c1,4
< 'asdf'
< 'asdf'
< 'asdf'
< 'asdf'
---
> asdf
> asdf
> asdf
> asdf
mitlenatch
  • 21
  • 3
  • Looks cool and works for this simple example, but for some reason it keeps failing on me for bigger and more complex diffs, too lazy to debug it to figure out why. – Loknar Mar 10 '18 at 14:03
1

You can without doupt recreate the desired syntax output using difflib but it might take some devious steps to simulate perfectly.

If this specific output syntax is not necessary you might consider the following solution:

import difflib
def generate_readable_diff_string(str_a, str_b):
    return ''.join(
        difflib.unified_diff(
            str_a.splitlines(True),
            str_b.splitlines(True),
            lineterm='\n'
        )
    )

For your foo and baz this function produces the following result:

--- 
+++ 
@@ -1,4 +1,4 @@
-'asdf'
-'asdf'
-'asdf'
-'asdf'
+asdf
+asdf
+asdf
+asdf
Loknar
  • 1,169
  • 2
  • 13
  • 38