Python:如何比较两个二进制文件?

Tre*_*ith 10 python debugging diff instrumentation hex

在 python 中,我需要打印两个二进制文件的差异。我正在看difflib.Differ哪个有很多作用。

但是,不同假设是文本行,因此输出不会列出字节索引和十六进制值差异。

我需要的是具有哪些字节不同、字节如何不同、两个字节的实际十六进制值的输出。

在Python中,如何比较两个二进制文件(输出:字节差异索引、两个字节的十六进制值)?

我正在做类似的事情:

# /usr/bin/env python2
import difflib
x = open('/path/to/file1', 'r').read()
y = open('/path/to/file2', 'r').read()
print '\n'.join(difflib.Differ().compare(x, y))
Run Code Online (Sandbox Code Playgroud)

但这不会输出差异所在的字节索引。并且它不打印十六进制值。

Tre*_*ith -2

shell 命令cmp已经完全满足了我的需要/想要。在 Python 中重新发明该功能将需要更多的精力/代码/时间......所以我只是从 Python 调用命令:

#!/usr/bin/env python2
import commands
import numpy as np
def run_cmp(filename1, filename2):
    cmd = 'cmp --verbose %s %s'%(filename1, filename2)
    status, output = commands.getstatusoutput(cmd) # python3 deprecated `commands` module FYI
    status = status if status < 255 else status%255
    if status > 1:
        raise RuntimeError('cmp returned with error (exitcode=%s, '
                'cmd=\"%s\", output=\n\"%s\n\")'%(status, cmd, output))
    elif status == 1:
        is_different = True
    elif status == 0:
        is_different = False
    else:
        raise RuntimeError('invalid exitcode detected')
    return is_different, output
if __name__ == '__main__':
    # create two binary files with different values
    # file 1
    tmp1 = np.arange(10, dtype=np.uint8)
    tmp1.tofile('tmp1')
    # file 2
    tmp2 = np.arange(10, dtype=np.uint8)
    tmp2[5] = 0xFF
    tmp2.tofile('tmp2')
    # compare using the shell command 'cmp'
    is_different, output = run_cmp(filename1='tmp1', filename2='tmp2')
    print 'is_different=%s, output=\n\"\n%s\n\"'%(is_different, output)
Run Code Online (Sandbox Code Playgroud)