Can't work out why I'm getting NameError: name 'thread' is not defined
Question: I've downloaded this .py file and I'm trying to get it to run. However,
everytime I do I get the following callback error and I'm at a loss to work
out what is causing it. I'm running Python 3.4.1 if that's any help, but as
far as I can see it should all work. The error I get is:

    
    
    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
    

As far as I can see though, this error shouldn't be happening. I am new to
Python so forgive me if the answer is something stupid. Thank you!

    
    
    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()
    


Answer: Try adding `import _thread` as well. Currently you're importing a few classes
from the [`threading`
module](https://docs.python.org/3/library/threading.html), which is different
from the [`thread`
module](https://docs.python.org/3/library/_thread.html#module-_thread). You'll
also want to change the call to:

    
    
            self.lock = _thread.allocate_lock()
    

Here's [an example in the Python
docs](https://docs.python.org/3/library/_thread.html#_thread.lock.locked).

As the Python docs recommend, it's a good idea to prefer the `threading`
module as it's higher level and won't break if you try to run the code in
Python 2. I would recommend looking into the [`Lock`
class](https://docs.python.org/3/library/threading.html#lock-objects).

