2015-11-20 104 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

相關問題