python - 与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
解决方案
问题来自您如何在Python
.
简短的回答:
你需要改变
gzip.open(in_file, "rb")
经过
open(in_file, "rb")
您将获得相同的 MD5 和。
长答案:
gzip.open()
将解压缩您的.gz
文件并以rb
模式读取其内容。但同时,md5sum
会处理压缩文件的MD5和。因此,它会导致不同的 MD5 和值。
如何解决这个问题?简单地说,open
压缩文件rb
并在不解压缩的情况下得到它的 MD5 和。
推荐阅读
- java - 如何在 Java 中的两行代码之间创建延迟?
- exchangewebservices - 在 EWS 中绑定和加载文件夹
- azure-devops - 克隆 git 存储库时无法解析主机:dev.azure.com
- python - 使用 SQLAlchemy 自动处理单行与多行
- python - DDQN 无法解决井字游戏
- python - 使用 str.rsplit 格式化列会将一些列名更改为 NAN
- c# - WPF MVVM 报告另一个类的进度?
- java - SpringApplication.run intellij 中的编译错误
- c++ - 一个头库中的错误
- javascript - 使用 angularJS 值显示和隐藏 HTML