简体   繁体   English

Python:为什么会出现NameError?

[英]Python: why am I getting a NameError?

I have the following code: 我有以下代码:

from crypt import crypt
import itertools
from string import ascii_letters, digits

def decrypt(all_hashes, salt, charset=ascii_letters + digits + "-"):
     products = (itertools.product(charset, repeat=r) for r in range(8))
     chain = itertools.chain.from_iterable(products)
     for candidate in chain:
         hash = crypt(candidate, salt)
         if hash in all_hashes:
              yield candidate, hash
              all_hashes.remove(hash)
              if not all_hashes:
                 return

all_hashes = 'aaRrt6qwqR7xk', 'aaacT.VSMxhms' , 'aaWIa93yJI9kU', /
'aakf8kFpfzD5E', 'aaMOPiDnXYTPE', 'aaz71s8a0SSbU', 'aa6SXFxZJrI7E', /
'aa9hi/efJu5P.', 'aaBWpr07X4LDE', 'aaqwyFUsGMNrQ', 'aa.lUgfbPGANY', /
'aaHgyDUxJGPl6', 'aaTuBoxlxtjeg', 'aaluQSsvEIrDs', 'aajuaeRAx9C9g', /
'aat0FraNnWA4g', 'aaya6nAGIGcYo', 'aaya6nAGIGcYo', 'aawmOHEectP/g', /
'aazpGZ/jXGDhw', 'aadc1hd1Uxlz.', 'aabx55R4tiWwQ', 'aaOhLry1KgN3.', /
'aaGO0MNkEn0JA', 'aaGxcBxfr5rgM', 'aa2voaxqfsKQA', 'aahdDVXRTugPc', /
'aaaLf47tEydKM', 'aawZuilJMRO.w', 'aayxG5tSZJJHc', 'aaPXxZDcwBKgo', /
'aaZroUk7y0Nao', 'aaZo046pM1vmY', 'aa5Be/kKhzh.o', 'aa0lJMaclo592', /
'aaY5SpAiLEJj6', 'aa..CW12pQtCE', 'aamVYXdd9MlOI', 'aajCM.48K40M.', /
'aa1iXl.B1Zjb2', 'aapG.//419wZU'


all_hashes = set(all_hashes)
salt = 'aa'
for candidate, hash in decrypt(all_hashes, salt):
     print 'Found', hash, '! The original string was', candidate

And when I go to run it i get the following traceback error: 当我运行它时,出现以下回溯错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in decrypt
NameError: must be string, not tuple

I think it has something to do with my "all_hashes" variable but if I take out the commas all the different hashes are stored as one long string 我认为这与我的“ all_hashes”变量有关,但是如果我取出逗号,则所有不同的哈希将存储为一个长字符串

Someone please shed some light, thanks in advance 有人请阐明一下,在此先感谢

The product s are tuples, like product是元组,例如

('g', 'g', 'g', 'e', 'a', 'b', 'f')

and crypt expects a string. crypt需要一个字符串。

Transform your tuples to strings before passing them to crypt , 将元组转换为字符串,然后再将其传递给crypt

 for candidate in chain:
     hash = crypt((''.join(candidate)), salt)

(thanks to Joel Cornett for the nice transformation to string and to HVNSweeting for the improvement on that.) (感谢Joel Cornett很好地将其转换为字符串, 并对HVNSweeting进行了改进)。

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

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