Python在Windows系统计算大文件的SHA-1哈希时崩溃
我想请大家帮我看看这个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()
* 更新 *
这是一个可以计算大文件SHA-1哈希值的Python脚本。感谢Ignacio Vazquez-Abrams指出了问题,感谢Tom Zych提供了代码。
使用方法很简单,只需将要计算哈希值的文件拖放到脚本上。或者,你也可以使用命令提示符,输入:
SHA-1HashGen.py Path&File
其中SHA-1HashGen.py是脚本的文件名,Path&File是你要计算哈希值的文件的路径和文件名。
或者把脚本放到“发送到”文件夹(在Windows系统中,可以通过shell:sendto访问)中,这样就可以在右键菜单中选择它。
2 个回答
9
(这是对彼得评论“剩下2GB”的回应。)
我觉得伊格纳西奥说得没错。试试把读取/更新的那一行换成这个:
while True:
buf = File.read(0x100000)
if not buf:
break
SHA1Hash.update(buf)
10
不要一次性把文件全部读进来,这样会占用系统的所有内存。可以试着每次读取大约16MB的数据。
data = File.read(16 * 1024 * 1024)