[英]Python: How to compare two binary files?
在 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 比較時,它會將每個 char 放入一個數組中,並在其前面加上一個 + 或 - 。 下面比較 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.