[英]How to solve name error not defined?
I am using hashing functions to calculate hash for various files. 我正在使用哈希函数来计算各种文件的哈希。 This is the code but I'm getting name error for "options" not defined. 这是代码,但未定义“选项”时出现名称错误。 I don't think I'm doing it right.Any suggestions? 我认为我做的不对,有什么建议吗? I'm using options before in the code so whats the problem? 我在代码中使用了选项,然后又出了什么问题?
#!/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()
Your input from the following line will be a string: 您在以下行中输入的内容将是一个字符串:
num = input("Select the hashing method you wish to use:\n 1. MD5\n 2. SHA1\n 3. SHA256\n")
you need to change your options to this: 您需要更改以下选项:
options = {
'1': calcMd5Hash,
'2': calcSHA1Hash,
'3': calcSHA256Hash,
}
Also, you could strip 'num' of any white space, just by doing: 另外,只需执行以下操作,即可去除任何空格的“ num”:
num = num.strip()
This is how your main function should look like: 这是您的主要功能的外观:
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.