无法解决为什么我会收到NameError:name' thread'没有定义

时间:2014-08-28 21:13:07

标签: python multithreading

我已下载此.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 个答案:

答案 0 :(得分:2)

尝试添加import _thread。目前,您正在从threading module导入一些类,这与thread module不同。您还需要将呼叫更改为:

        self.lock = _thread.allocate_lock()

这是an example in the Python docs

正如Python文档所推荐的那样,最好选择threading模块作为更高级别,如果尝试在Python 2中运行代码则不会中断。我建议查看{{ 3}}