如何打印统一diff格式的两个多行字符串的比较?

时间:2009-05-10 12:51:13

标签: python diff unified-diff

你知道任何有助于这样做的图书馆吗?

我会编写一个函数,以统一的diff格式打印两个多行字符串之间的差异。这样的事情:

def print_differences(string1, string2):
    """
    Prints the comparison of string1 to string2 as unified diff format.
    """
    ???

用法示例如下:

string1="""
Usage: trash-empty [days]

Purge trashed files.

Options:
  --version   show program's version number and exit
  -h, --help  show this help message and exit
"""

string2="""
Usage: trash-empty [days]

Empty the trash can.

Options:
  --version   show program's version number and exit
  -h, --help  show this help message and exit

Report bugs to http://code.google.com/p/trash-cli/issues
"""

print_differences(string1, string2)

这应该打印出类似的东西:

--- string1 
+++ string2 
@@ -1,6 +1,6 @@
 Usage: trash-empty [days]

-Purge trashed files.
+Empty the trash can.

 Options:
   --version   show program's version number and exit

2 个答案:

答案 0 :(得分:26)

这就是我解决的问题:

def _unidiff_output(expected, actual):
    """
    Helper function. Returns a string containing the unified diff of two multiline strings.
    """

    import difflib
    expected=expected.splitlines(1)
    actual=actual.splitlines(1)

    diff=difflib.unified_diff(expected, actual)

    return ''.join(diff)

答案 1 :(得分:23)

您是否看过内置的python模块difflib? 看看这个example