在为Windows操作系统中的大文件计算SHA-1哈希时,Python崩溃

Pet*_*ter 6 python hash sha1 large-files

我想知道我是否可以对这个python脚本有一些新的眼光.它适用于中小型文件,但是大型文件(4-8GB左右)在运行几分钟后会出现无法解决的崩溃.

这里有压缩脚本

要么:

import sys
import msvcrt
import hashlib

#Print the file name (and its location) to be hashed  
print 'File:  ' + str(sys.argv[1])

#Set "SHA1Hash" equal to SHA-1 hash
SHA1Hash = hashlib.sha1()

#Open file specified by "sys.argv[1]" in read only (r) and binary (b) mode
File = open(sys.argv[1], 'rb')

#Get the SHA-1 hash for the contents of the specified file
SHA1Hash.update(File.read())

#Close the file
File.close()

#Set "SHA1HashBase16" equal to the hexadecimal of "SHA1Hash"
SHA1HashBase16 = SHA1Hash.hexdigest()

#Print the SHA-1 (hexadecimal) hash of the file
print 'SHA-1: ' + SHA1HashBase16

#Make a blank line
print ' '

#Print "Press any key to continue..."
print 'Press any key to continue...'

#"Press any key to continue..." delay
char=0
while not char:
    char=msvcrt.getch()
Run Code Online (Sandbox Code Playgroud)

*更新*

使用python脚本计算大文件的SHA-1哈希值.感谢Ignacio Vazquez-Abrams指出错误和Tom Zych的代码.

拉链源在这里

使用简单地拖放要在脚本顶部进行哈希处理的文件.或者,您可以使用命令提示符,使用:

SHA-1HashGen.py Path&File 
Run Code Online (Sandbox Code Playgroud)

SHA-1HashGen.py是脚本的文件名,Path&File是要散列的文件的路径和文件名.

或者将脚本放入SendTo文件夹(在Windows操作系统中; shell:sendto)以将其作为右键单击选项.

Ign*_*ams 9

停止一次阅读文件; 你正在消耗系统上的所有内存.请改为读入16MB左右的块.

data = File.read(16 * 1024 * 1024)
Run Code Online (Sandbox Code Playgroud)


Tom*_*ych 8

(回应彼得的评论,留下2 GB.)

我怀疑伊格纳西奥是对的.尝试用以下方法替换读取/更新行:

while True:
    buf = File.read(0x100000)
    if not buf:
        break
    SHA1Hash.update(buf)
Run Code Online (Sandbox Code Playgroud)