为什么会出现NameError错误?

9

I have the following code:

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

def decrypt(all_hashes, salt, charset=ascii_letters + digits + "-"):
     products = (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

当我运行它时,我会得到以下回溯错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in decrypt
NameError: global name 'itertools' is not defined

我无法弄清楚为什么会发生这种情况。

有人能够解释一下吗?非常感谢!


我认为你在发布的代码中存在缩进错误。(导入部分被缩进了,但实际上不应该) - mgilson
3个回答

17

看起来你没有导入itertools模块...

from itertools import product

这样做并不起作用,因为它只会将product直接引入到你的模块命名空间中(但你的模块仍然对其他itertools内容一无所知)。只需添加:

import itertools

在你的脚本顶部添加这行代码,错误应该就会消失,因为现在你已经将 itertools 命名空间引入到你的模块命名空间下,并使用名称 itertools。换句话说,要访问 chain 函数,你需要使用 itertools.chain(就像你在上面的脚本中使用的那样)。


当我这样做时,它会显示相同的内容,但是关于“产品”。 - user1816467
1
你可以同时在顶部引用 import itertoolsfrom itertools import product,但你可能只想使用其中一个。在这种情况下,如果你只使用 import itertools,那么你需要将 product 更改为 itertools.product - mgilson

4
您想要的是:

要么:

from itertools import chain, product

您可以使用chainproduct,或者:

import itertools

并且使用 itertools.chainitertools.product

2
import itertools

from itertools import izip_longest

这帮助我使用 itertools,然后能够使用 izip_longest 迭代不同长度的数组。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接