[英]Python hashlib md5 different output and slow speed compared to bash md5sum?
我有两个要解决的问题。 1)当我运行 hashlib md5 时,我得到的 output 与我在 bash 中运行 md5sum 时不同。 2) 在 python 中运行程序比 bash 需要更长的时间。
另外,我有一个 md5sum 值表,我想将此测试文件和其他文件匹配到。 我的测试用例中的 bash output 与表中提供的值匹配。 所以理想情况下,我想让 python output 与之匹配。
这是我到目前为止所尝试的:
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)
Output:
b'b0a25d66a1a83582e088f062983128ed test.fastq.gz\n'
Time elapsed: 0.007306102000256942
cfda2978db7fab4c4c5a96c61c974563
Time elapsed: 95.02966231200026
问题来自您如何在Python
中打开文件。
简短的回答:
你需要改变
gzip.open(in_file, "rb")
经过
open(in_file, "rb")
您将获得相同的 MD5 和。
长答案:
gzip.open()
将解压缩您的.gz
文件并以rb
模式读取其内容。 但同时md5sum
会处理压缩文件的 MD5 和。 因此,它会导致不同的 MD5 和值。
如何解决这个问题? 简单地说,在rb
中open
压缩文件并得到它的 MD5 和,而不用解压缩它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.