Python hashlib md5 与 bash md5sum 相比不同的输出和较慢的速度?

Python hashlib md5 different output and slow speed compared to bash md5sum?

我有两个问题要解决。 1) 当我 运行 hashlib md5 时,我得到的输出与我在 bash 中 运行 md5sum 时得到的输出不同。 2) 运行 python 中的程序比 bash 中的程序花费的时间长得多。

此外,我有一个 table 的 md5sum 值,我想将此测试文件和其他文件匹配。我的测试用例中的 bash 输出与我在 table 中提供的值匹配。所以理想情况下,我想让 python 输出与之匹配。

这是我到目前为止尝试过的方法:

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")

来自

open(in_file, "rb")

您将获得相同的 MD5 和。

长答案:

gzip.open() 将解压缩您的 .gz 文件并以 rb 模式读取其内容。但与此同时,md5sum 将处理压缩文件的 MD5 和。因此,它会导致不同的 MD5 和值。

如何解决这个问题?简单地说,open rb 中的压缩文件并在不解压缩的情况下获取它的 MD5 和。