在 Windows 操作系统中计算大文件的 SHA1 哈希值时 Python 崩溃

标签 python hash large-files sha1

我想知道我是否可以对这个 python 脚本有一些新的看法。它适用于中小型文件,但适用于大型文件(4-8GB 左右),运行几分钟后会莫名其妙地崩溃。

Zipped script here

或者:

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 提供代码。

Zipped source here

要使用,只需将要散列的文件拖放到脚本之上即可。或者,您可以使用命令提示符并使用:

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/

相关文章:

mysql - 如何在mysql中索引innodb文本?

c# - FileStream 在 128 字节后从 A 读取并写入 B C#

python - SqlAlchemy 1.0.0 添加 'AND NULL' 以加入未定义外键的位置

python - postgresql+python : how to adapt for copy_from?

language-agnostic - 在某些条件下,密码散列是内射的吗?

Java - 跨服务器散列/加密

c# - 未设置 TransferEncodingChunked 时 HttpClient 抛出 OutOfMemory 异常

ios - 如何在后台线程(Swift)上有效地将大文件写入磁盘

python - 禁用文件的所有 Pylint 警告

python - 如何在python中执行shell命令文件