无法理解为什么我得到NameError: name 'thread'未定义

-2 投票
1 回答
2184 浏览
提问于 2025-04-18 18:54

我下载了一个.py文件,想让它运行。但是每次我尝试运行的时候,都会出现一个回调错误,我搞不清楚是什么原因导致的。我现在使用的是Python 3.4.1,如果这有帮助的话。不过从我所看到的情况来看,这个文件应该是可以正常工作的。我遇到的错误是:

C:\Users\******\Documents\****\>wkreator.py -d .\PsycOWPA -o .\PsycOWPA. txt Traceback (most recent call last):   File "C:\Users\******\Documents\****\>", line 273, in <modu le>
    main = WordlistKreator()   File "C:\Users\******\Documents\****\>", line 21, in
__init
__
    self.lock = thread.allocate_lock() NameError: name 'thread' is not defined

不过从我所了解的情况来看,这个错误不应该出现。我刚开始学习Python,如果答案很简单请多多包涵。谢谢!

checkinterval = 1000 ### CHANGE THIS IF YOU WANT MORE PRECISION INSTEAD OF SPEED!!! ###
import fnmatch
import sys
import time
import os
from threading import Thread, Lock
import math

class WordlistKreator(object):
    """
    This is a little module that can merge or split wordlists. You can import it and set the
    runningvar, and call run. To launch it from a shell, instantiate the class, call convert
    to setup the runningvars dict with the cmdline args, then run. You need to import os,
    sys, thread and time to use it.
    """

    def __init__(self):
        self.RunningVars = {'Mode':'merge', 'Dir':'', 'InWordlists':[], 'OutputWordlist':'', 'Suffix':0,
                            'WPAMode':0, 'Size':0}
        self.Done = 0
        self.lock = thread.allocate_lock()
        self.OnWin = 0

    def convert(self):
        if fnmatch.fnmatch(sys.platform, '*win*'):
            self.OnWin = 1
        self.stampcomm('Processing cmdline arguments...')
        actual = 0
        for args in sys.argv:
            actual = actual+1
            if args == '-m':
                self.RunningVars['Mode'] = sys.argv[actual]
            elif args == '-d':
                self.RunningVars['Dir'] = sys.argv[actual]
            elif args == '-i':
                if self.RunningVars['Mode'] == 'merge':
                    for wordlist in sys.argv[actual].split(':'):
                        self.RunningVars['InWordlists'].append(wordlist)
                if self.RunningVars['Mode'] == 'split':
                    self.RunningVars['InWordlists'].append(sys.argv[actual])
            elif args == '-o':
                self.RunningVars['OutputWordlist'] = sys.argv[actual]
            elif args == '-s':
                self.RunningVars['Suffix'] = int(sys.argv[actual])
            elif args == '-z':
                self.RunningVars['Size'] = (int(sys.argv[actual])*1024)*1024
            elif args == '-w':
                self.RunningVars['WPAMode'] = 1
        if self.RunningVars['InWordlists'] == [] and self.RunningVars['Mode'] == 'merge':
            for wordlist in os.listdir(self.RunningVars['Dir']):
                self.RunningVars['InWordlists'].append(os.path.split(wordlist)[1])

    def run(self):
        self.stampcomm('Starting the %s operations...'% self.RunningVars['Mode'])
        if self.RunningVars['Mode'] == 'merge':
            self.outlist = open(self.RunningVars['OutputWordlist'], 'a+')
            thread.start_new(self.merge, ())
            self.mergestats()
            self.outlist.close()
            self.stampcomm('Job completed!!!')
            exit(0)
        elif self.RunningVars['Mode'] == 'split':
            self.mainlist = open(self.RunningVars['InWordlists'][0], 'r')
            thread.start_new(self.split, ())
            self.splitstats()
            self.mainlist.close()
            self.stampcomm('Job completed!!!')
            exit(0)
        else:
            self.stampcomm('An error have occured, check your arguments and restart!!!')
            exit(0)

    def merge(self):
        while True:
            try:
                self.lock.acquire(1)
                self.actuallist = self.RunningVars['InWordlists'].pop()
                if self.OnWin == 1:
                    tomerge = open(self.RunningVars['Dir'] + '\\' + self.actuallist, 'r')
                else:
                    tomerge = open(self.RunningVars['Dir'] + '/' + self.actuallist, 'r')
                self.lock.release()
                while True:
                    try:
                        if self.RunningVars['WPAMode'] == 1:
                            word = tomerge.next()
                            if self.OnWin == 1:
                                if len(word) >= 10 and len(word) <= 65: # Add \r\n to the chars count;
                                    self.outlist.write(word)
                            else:
                                if len(word) >= 9 and len(word) <= 64: # Add \n to the chars count;
                                    self.outlist.write(word)
                        else:
                            self.outlist.write(tomerge.next())
                    except StopIteration:
                        break
                tomerge.close()
            except IndexError:
                break
        self.Done = 1

    def split(self):
        outpath, outname = os.path.split(self.RunningVars['OutputWordlist'])
        extention = outname[-4:]
        outname = outname[:-4]
        if self.OnWin == 1:
            outpath = outpath + '\\'
        else:
            outpath = outpath + '/'
        requiredlist = int(math.ceil(float(os.path.getsize(self.RunningVars['InWordlists'][0])) / \
                                     float(self.RunningVars['Size'])))
        self.requiredliststat = requiredlist
        list2work = []
        if self.RunningVars['Suffix'] == 0:
            try:
                for listnum in range(requiredlist):
                    self.listnumstat = listnum
                    actuallistname = outpath + outname + str(listnum) + extention
                    self.actuallistnamestat = os.path.split(actuallistname)[1]
                    actualout = open(actuallistname, 'w')
                    loopcount = 0
                    while True:
                        if loopcount == checkinterval:
                            if os.path.getsize(actuallistname) >= self.RunningVars['Size']:
                                break
                            loopcount = 0
                        actualout.write(self.mainlist.next())
                        loopcount = loopcount + 1
            except StopIteration:
                actualout.close()
                self.Done = 1
        else:
            try:
                for listnum in range(requiredlist):
                    self.listnumstat = listnum
                    actuallistname = outpath + outname + str(listnum).zfill(self.RunningVars['Suffix']) + extention
                    self.actuallistnamestat = os.path.split(actuallistname)[1]
                    actualout = open(actuallistname, 'w')
                    loopcount = 0
                    while True:
                        if loopcount == 10000:
                            if os.path.getsize(actuallistname) >= self.RunningVars['Size']:
                                break
                            loopcount = 0
                        actualout.write(self.mainlist.next())
                        loopcount = loopcount + 1
            except StopIteration:
                actualout.close()
                self.Done = 1

    def stampcomm(self, message):
        if self.OnWin == 1:
            print('-=[' + time.asctime()[4:-8] + ']=-' + message)
        else:
            print('╟─' + time.asctime()[4:-8] + '─╫─' + message)

    def mergestats(self):
        Counter = 0
        while self.Done == 0:
            if Counter == 300:
                self.lock.acquire(1)
                self.stampcomm('Only %d more wordlist(s) to process... Actually working on %s' \
                               % (len(self.RunningVars['InWordlists']), self.actuallist))
                self.lock.release()
                Counter = 0
            else:
                time.sleep(1)
                Counter = Counter + 1

    def splitstats(self):
        Counter = 0
        while self.Done == 0:
            if Counter == 300:
                self.lock.acquire(1)
                self.stampcomm('Currently %d list done out of %d... Actually working on %s' \
                               % (self.listnumstat, self.requiredliststat, self.actuallistnamestat))
                self.lock.release()
                Counter = 0
            else:
                time.sleep(1)
                Counter = Counter + 1

if __name__ == '__main__':

    if fnmatch.fnmatch(sys.platform, '*win*'):
        usage = r"""

                      --== wkreator ==--

 Wordlist Kreator(wkreator)  Copyright (C) 2011  Mikael Lavoie

 This program comes with ABSOLUTELY NO WARRANTY; This is free
 software, and you are welcome to redistribute it under certain
 conditions; Read GNU_GPL-3.0.pdf in the program directory for
 more informations.

 This program take an input dir, or multiple file seperated by :
 and make one big file of them. It can also be used to split one
 big wordlist into smaller chunks to use them one by one, during
 a period of time, instead on crunching it one shot.

 Usage:   wkreator -m The mode of operation, that can be <merge>
                      or <split>.
                   -d The input directory. If used alone, all
                      .txt file in that directory will be used as
                      input files. Else you must provide all
                      wordlist name seperated by <:> using the -i
                      switch. To split use only -i.
                   -i The input wordlist(s) separated by : if
                      more than one. Ex: word1.txt:word2.txt:...
                      To split, enter full path to main list.
                   -o The output path and file name. If you enter
                      a path to an existing file, the inputs
                      wordlists will be appended to it.
                   -s The desired suffix number lenght, if you
                      desire zero padded numbers as suffix for
                      splitted wordlists.
                   -z The size in MB of the output wordlists in
                      split mode.
                   -w This toggle the WPA mode on; All < 8 and
                      > 63 chars words will be discarded.


              --== By Mikael Lavoie in 2011 ==--
"""
    else:
        usage = r"""
                          ╔════════════╗
┌─────────────────────────╢  wkreator  ╟───────────────────────────┐
│                         ╚════════════╝                           │
│ Wordlist Kreator(wkreator)  Copyright (C) 2011  Mikael Lavoie    │
│                                                                  │
│ This program comes with ABSOLUTELY NO WARRANTY; This is free     │
│ software, and you are welcome to redistribute it under certain   │
│ conditions; Read GNU_GPL-3.0.pdf in the program directory for    │
│ more informations.                                               │
│                                                                  │
│ This program take an input dir, or multiple file seperated by :  │
│ and make one big file of them. It can also be used to split one  │
│ big wordlist into smaller chunks to use them one by one, during  │
│ a period of time, instead on crunching it one shot.              │
│                                                                  │
│ Usage:   wkreator -m The mode of operation, that can be <merge>  │
│                      or <split>.                                 │
│                   -d The input directory. If used alone, all     │
│                      .txt file in that directory will be used as │
│                      input files. Else you must provide all      │
│                      wordlist name seperated by <:> using the -i │
│                      switch. To split use only -i.               │
│                   -i The input wordlist(s) separated by : if     │
│                      more than one. Ex: word1.txt:word2.txt:...  │
│                      To split, enter full path to main list.     │
│                   -o The output path and file name. If you enter │
│                      a path to an existing file, the inputs      │
│                      wordlists will be appended to it.           │
│                   -s The desired suffix number lenght, if you    │
│                      desire zero padded numbers as suffix for    │
│                      splitted wordlists.                         │
│                   -z The size in MB of the output wordlists in   │
│                      split mode.                                 │
│                   -w This toggle the WPA mode on; All < 8 and    │
│                      > 63 chars words will be discarded.         │
│                   ╔══════════════════════════╗                   │
└───────────────────╢ By Mikael Lavoie in 2011 ╟───────────────────┘
                    ╚══════════════════════════╝
"""

###### The Shell Args Interpreter ######

    if len(sys.argv) > 1 and sys.argv[1] == '--help' or len(sys.argv) == 1 or sys.argv[1] == '-h':
        print(usage)
        exit(0)
    main = WordlistKreator()
    main.convert()
    main.run()

1 个回答

2

试着加上 import _thread。现在你正在从 threading 模块 导入一些类,但这个模块和 thread 模块 是不一样的。你还需要把调用改成:

        self.lock = _thread.allocate_lock()

这里有一个 Python 文档中的例子

正如 Python 文档所推荐的,使用 threading 模块是个好主意,因为它是更高级的模块,如果你在 Python 2 中运行代码也不会出问题。我建议你看看 Lock

撰写回答