我有这段代码可以计算给定文件的 MD5 和 SHA1 值并将其显示在控制台中。它完成了它的工作,但是我收到了错误消息:
Traceback (most recent call last):
File "C:\Program Files (x86)\Aptana\workspace\Ipfit5\Semi-Definitief\test6.py",
line 64, in <module>
hash_file(woord)
File "C:\Program Files (x86)\Aptana\workspace\Ipfit5\Semi-Definitief\test6.py",
line 29, in hash_file
hash_file(sys.argv[1]);
IndexError: list index out of range
代码如下所示:
import sys, hashlib, os
def hash_file(filename): #Calculate MD5 and SHA1 hash values of a given file
# Create hash objects for MD5 and SHA1.
md5_hash = hashlib.md5()
sha1_hash = hashlib.sha1()
filename = r"C:/this.png"
# Read the given file by 2K blocks. Feed blocks
# into into the hash objects by "update(data)" method.
fp = open(filename,'rb')
while 1:
data = fp.read(2048)
if not data:
break
else:
md5_hash.update(data)
sha1_hash.update(data)
fp.close()
print "The MD5 hash of your file is"
print filename,":", md5_hash.hexdigest();
print "The SHA1 hash of your file is"
print filename,":", sha1_hash.hexdigest();
if __name__ == '__main__':
hash_file(sys.argv[1]);
hash_file(woord)
我将函数称为 (wood),因为这是稍后在脚本中定义的内容,但它与函数 hash_file(filename) 中的文件名基本相同。
当它确实向我显示哈希值以及如何摆脱它时,为什么我会收到此错误?
编辑:我知道这与 if name == ' main ': hash_file(sys.argv[1]); 但我无法弄清楚。
任何帮助是极大的赞赏