在 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))
但这不会输出差异所在的字节索引。并且它不会打印十六进制值。
当 difflib 进行比较时,它将每个字符放入一个数组中,前面有 + 或 - 。下面比较 x 和 y,然后我们查看输出:
d = difflib.Differ()
e = d.compare(x,y) #set the compare output to a variable
for i in range(0,len(e)):
if i.startswith("-"): #if that char start with "-" is not a match
print(i + "index is different")
字符将以不匹配的“-”开头。 “+”表示它们匹配。
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)