2015-11-20 103 views
-1

我正在使用散列函数来计算各种文件的散列。这是代码,但我得到未定义的“选项”的名称错误。我认为我没有做对。任何建议?我之前在代码中使用了选项,所以最新的问题是什么?如何解决未定义的名称错误?

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

您的问题包含带有多个缩进错误的代码。我们无法猜测这个代码出现哪些问题,因为您错误地粘贴了它,以及您*需要帮助的其他部分。请修复缩进。常用的方法是粘贴您的代码,然后选择粘贴的块,然后按ctrl-K将它缩进为代码。也许在粘贴之前确保你有空格而不是制表符。 – tripleee

回答

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() 
+0

我加了引号,但我得到的选项没有为打印线 – user2127184

+0

Traceback(最近调用最后一个)定义: 文件“Calc_Hash.py”,第51行,在 print(“文件的MD5哈希命名为:“+ str(sys.argv [1])+”is:“+ options [num](sys.argv [1])) NameError:name'options'is not defined – user2127184

+0

请参阅我粘贴的主函数以上。另外,您可能需要在其他地方修理缩进。 – sisanared

相关问题