ファイルのリストのチェックサムを計算し、それを参照ファイルと比較するプログラムを書いています。
メソッドのバイトバッファーを、使用hashfile
と同じ単位のファイルサイズに変換しようとしos.stat(path).st_size
ているので、それに応じてtqdm進行状況バーを更新できます。(ここで最後の例を実装しようとしています)
私は多くのことを試しました( len(buf)
:合計よりもはるかに大きな処理サイズを与えますint.from_bytes()
:OverflowError - intが大きすぎてfloatに変換できませんstruct.unpack_from(buf)
:一度に1バイトを読み取る必要があり、バイトを変換するにはさまざまな関数が必要です)しかしこれまでのところ何も機能しませんでした。何を検索すればよいか、見つけたソリューションを実装するには、バイトを十分に理解していないようです。
コードからの抜粋を次に示します。
import hashlib
import os
from tqdm import tqdm
# calculate total size to process
self.assets_size += os.stat(os.path.join(root, f)).st_size
def hashfile(self, progress, afile, hasher, blocksize=65536):
"""
Checksum buffer
:param progress: progress bar object
:param afile: file to process
:param hasher: checksum algorithm
:param blocksize: size of the buffer
:return: hash digest
"""
buf = afile.read(blocksize)
while len(buf) > 0:
self.processed_size += buf # need to convert from bytes to file size
hasher.update(buf)
progress.update(self.processed_size) # tqdm update
buf = afile.read(blocksize)
afile.seek(0)
return hasher.digest()
def process_file(self, progress, fichier):
"""
Checks if the file is in the reference dictionary;
If so, checks if the size of the file matches the one stored in the dictionary;
If so, calculates the checksum of the file and compares it to the one in the dictionary
:param progress: progress bar object
:param fichier: asset file to process
:return: string outcome of the process
"""
checksum = self.hashfile(progress, open(fichier, 'rb'), hashlib.sha1())
# check if checksum matches
return outcome
def main_process(self):
"""
Launches and monitors the process and writes a report of the results
:return: application end
"""
with tqdm(total=self.assets_size, unit='B', unit_scale=True) as pbar:
all_results = []
for f in self.assets.keys():
results = self.process_file(pbar, f)
all_results.append(results)
for r in all_results:
print(r)