Python hashlib md5与bash md5sum相比,输出不同且速度较慢?
我有两个问题要解决。1) 当我运行hashlibmd5时,得到的输出与在bash中运行md5sum时不同。2) 在python中运行该程序所需的时间比bash长得多 另外,我有一个md5sum值表,我想匹配这个测试文件和其他文件。测试用例中的bash输出与表中提供的值匹配。因此,理想情况下,我希望python输出与之匹配 以下是我迄今为止所尝试的:Python hashlib md5与bash md5sum相比,输出不同且速度较慢?,python,python-3.x,bioinformatics,Python,Python 3.x,Bioinformatics,我有两个问题要解决。1) 当我运行hashlibmd5时,得到的输出与在bash中运行md5sum时不同。2) 在python中运行该程序所需的时间比bash长得多 另外,我有一个md5sum值表,我想匹配这个测试文件和其他文件。测试用例中的bash输出与表中提供的值匹配。因此,理想情况下,我希望python输出与之匹配 以下是我迄今为止所尝试的: import os import hashlib import gzip import time import subprocess def ge
import os
import hashlib
import gzip
import time
import subprocess
def get_gzip_md5(in_file):
#gets the md5sum value for a given file
hash_md5 = hashlib.md5()
chunk = 8192
with gzip.open(in_file, "rb") as f:
while True:
buffer = f.read(chunk)
if not buffer:
break
hash_md5.update(buffer)
return hash_md5.hexdigest()
t0 = time.process_time()
out = subprocess.run("md5sum test.fastq.gz", shell=True, stdout=subprocess.PIPE)
print(out.stdout)
t1 = time.process_time() - t0
print("Time elapsed:",t1)
t0 = time.process_time()
md5 = get_gzip_md5("test.fastq.gz")
print(md5)
t1 = time.process_time() - t0
print("Time elapsed:",t1)
输出:
b'b0a25d66a1a83582e088f062983128ed test.fastq.gz\n'
Time elapsed: 0.007306102000256942
cfda2978db7fab4c4c5a96c61c974563
Time elapsed: 95.02966231200026
问题来自如何在
Python
中打开文件
简短回答:
你需要改变
gzip.open(in_file, "rb")
借
你将得到相同的MD5总和
长答案:
gzip.open()。但是,同时,md5sum
将处理压缩文件的MD5和。因此,它将导致不同的MD5和值
如何解决这个问题?简单地说,在rb
中打开压缩文件,在不解压缩的情况下得到它的MD5和。很容易看到它。。。而且很容易出错,因为它是一个微妙的细节在快速看。bash MD5正在计算原始压缩文件的校验和。通过对PythonMD5使用gzip.open
,可以解压缩文件,并相应地计算解压缩文件的MD5。
open(in_file, "rb")