Skip to main content
 首页 » 编程设计

按顺序散列大量文件时出现 Python 内存错误

2024年10月25日9虾米哥

基本上是为了练习/娱乐,我创建了一个包含所有文件的列表,对每个文件进行哈希处理并在列表中搜索重复项。这只是给我的;不管它有多糟糕。

我不断收到以下错误,

python(16563) malloc: *** mmap(size=140400698290176) failed (error code=12) 
*** error: can't allocate region 
*** set a breakpoint in malloc_error_break to debug 

脚本读取的是一个 22MB 的文本文件,我要散列的许多文件都是视频,通常但不总是低于 4GB。我不是一个好的程序员;我通常设计 UI/UX,所以内存、硬件、计算——这个 Jedi 不知道这些东西。

我使用的是 Mac (10.8.5);我有 32GB 的内存。 Python 以 64 位模式 (2.7) 运行。正在扫描 7 个卷;我的启动驱动器是最小的,它是 90GB SSD。

# This class mostly just calls os.stat and hashes the file 
class FileInspection: 
    def __init__(self, path): 
        self.path = path 
        self.hash = self.double_hash(path) 
        self.inspectable = True 
        stats = os.stat(path) 
        self.size = stats.st_size 
        self.last_mod = stats.st_mtime 
 
    def double_hash(self, path): 
        checksum = None 
        matching_checksums = False 
        match_attempts = 0 
        while not matching_checksums: 
            match_attempts += 1 
            fileData = open(self.path).read() 
            checksum1 = hashlib.md5(fileData).hexdigest() 
            checksum2 = hashlib.md5(fileData).hexdigest() 
            if checksum1 == checksum2: 
                checksum = checksum1 
                matching_checksums = True 
            elif match_attempts > 3: 
                self.hash = False 
                self.inspectable = False 
        return checksum 
 
 
# This is the main function call 
def masterList(self, path): 
        f = open(path, "r") 
        lines = f.readlines() 
        f.close() 
 
        f = open(path, "w") 
        for line in lines: 
            line = line[:-1] 
            fileInfo = FileInspection(line) 
            fileStr = 'f_{0} = {1}"checked":False, "path":"{2}", "inspectable":{3}, "hash":, "filesize":{4}, "lastmod":"{5}"{6}'.format(fileInfo.hash, "{", fileInfo.path, fileInfo.inspectable, fileInfo.hash, fileInfo.last_mod, "}") 
            f.write(fileStr) 
        f.close() 
 
masterList("/path/to/a/giant/list/of/files.txt") 

请您参考如下方法:

您可能正在运行 32 位 python 并试图将超过 4 GB 的数据加载到进程中。您可以尝试在 64 位 python 中运行代码,或者在 double_hash 函数中重构以下 md5 代码:

fileData = open(self.path).read() 
checksum1 = hashlib.md5(fileData).hexdigest() 
checksum2 = hashlib.md5(fileData).hexdigest() # Why calculate this twice? 

为此:

read_size = 1024 # You can make this bigger 
checksum1 = hashlib.md5() 
with open(self.path, 'rb') as f: 
    data = f.read(read_size) 
    while data: 
        checksum1.update(data) 
        data = f.read(read_size) 
checksum1 = checksum1.hexdigest() 
#continue using checksum1 

以这种方式生成 md5 将避免将整个文件加载到内存中。