繁体   English   中英

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

[英]How to solve name error not defined?

我正在使用哈希函数来计算各种文件的哈希。 这是代码,但未定义“选项”时出现名称错误。 我认为我做的不对,有什么建议吗? 我在代码中使用了选项,然后又出了什么问题?

#!/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()

您在以下行中输入的内容将是一个字符串:

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 = 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM