首页 > 解决方案 > 与bash md5sum相比,Python hashlib md5输出不同且速度慢?

问题描述

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

另外,我有一个 md5sum 值表,我想将此测试文件和其他文件匹配到。我的测试用例中的 bash 输出与我在表中提供的值相匹配。所以理想情况下,我想让 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

标签: pythonpython-3.xbioinformatics

解决方案


问题来自您如何在Python.

简短的回答:

你需要改变

gzip.open(in_file, "rb")

经过

open(in_file, "rb")

您将获得相同的 MD5 和。

长答案:

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

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


推荐阅读