我想知道我是否可以对这个 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是待哈希文件的路径和文件名。
或者将脚本放入 SendTo 文件夹(在 Windows 操作系统中;shell:sendto)以将其作为右键单击选项获取。
最佳答案
一次性停止读取文件;您正在消耗系统上的所有内存。改为读取 16MB 左右的 block 。
data = File.read(16 * 1024 * 1024)
关于在 Windows 操作系统中计算大文件的 SHA1 哈希值时 Python 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520585/