如何解决未定义的名称错误?

时间:2015-11-20 04:24:07

标签: python python-3.x hash

我正在使用散列函数来计算各种文件的散列值。这是代码,但我得到了"选项"的名称错误。没有定义的。我不认为我做得对。有什么建议吗?我之前在代码中使用了选项,所以问题是什么?

#!/usr/bin/python
import sys
import itertools
import hashlib

 # function  reads file and calculate the MD5 signature
 def calcMd5Hash(filename):
 hash = hashlib.md5()
  with open(filename) as f:
    for chunk in iter(lambda: f.read(4096), ""):
        hash.update(chunk)
    return hash.hexdigest()

# function  reads file and calculate the SHA1 signature
def calcSHA1Hash(filename):
hash = hashlib.sha1()
with open(filename) as f:
    for chunk in iter(lambda: f.read(4096), ""):
        hash.update(chunk)
    return hash.hexdigest()

# function  reads file and calculate the SHA256 signature
def calcSHA256Hash(filename):
hash = hashlib.sha256()
with open(filename) as f:
    for chunk in iter(lambda: f.read(4096), ""):
        hash.update(chunk)
return hash.hexdigest()

def main():
num = input("Select the hashing method you wish to use:\n 1. MD5\n 2. SHA1\n 

 3. SHA256\n")

options = {
    1: calcMd5Hash,
    2: calcSHA1Hash,
    3: calcSHA256Hash,
}

# test for enough command line arguments
if len(sys.argv) < 3:
    print("Usage python calculate_hash.py <filename>")
    return

hashString = options[num](sys.argv[1])

print("The MD5 hash of file named: "+str(sys.argv[1])+" is: "+options[num] 
(sys.argv[1]))

main()

1 个答案:

答案 0 :(得分:1)

以下行的输入将是一个字符串:

num = input("Select the hashing method you wish to use:\n 1. MD5\n 2. SHA1\n 3. SHA256\n")

您需要将选项更改为:

options = {
    '1': calcMd5Hash,
    '2': calcSHA1Hash,
    '3': calcSHA256Hash,
}

另外,你可以剥掉“数字”。任何空白区域,只需做:

num = num.strip()

这是你的主要功能应该是这样的:

def main():
    num = input("Select the hashing method you wish to use:\n 1. MD5\n 2. SHA1\n 3. SHA256\n").strip()
    options = {
      '1': calcMd5Hash,
      '2': calcSHA1Hash,
      '3': calcSHA256Hash,
    }

    # test for enough command line arguments
    if len(sys.argv) < 3:
      print("Usage python calculate_hash.py <filename>")
      return

    hashString = options[num](sys.argv[1])
    print("The MD5 hash of file named: " + str(sys.argv[1]) + " is: "+ hashString)

if __name__ == "__main__":
    main()