0

I'm trying to check a list of answers like so:

def checkAns(File, answer):
    answer = bytes(answer, "UTF-8")
    try:
        File.extractall(pwd=answer)
    except:
        pass
    else:
        print("[+] Correct Answer: " + answer.decode("UTF-8") + "\n")

def main():
    File = zipfile.ZipFile("questions.zip")
    ansFile = open("answers.txt")
    for line in ansFile.readlines():
        answer = line.strip("\n")
        t = Thread(target=extractFile, args=(File, answer))
        t.start()

Assume the correct answer is 4 and your list contains values 1 through 1000000. How do I get it to stop after it gets to 4 and not run through the remaining numbers in the list?

I have tried it several different ways:

else:
    print("[+] Correct Answer: " + answer.decode("UTF-8") + "\n")
        exit(0)

and also

try:
    File.extractall(pwd=answer)
        print("[+] Correct Answer: " + answer.decode("UTF-8") + "\n")
        exit(0)
except:
        pass

How do I get all the threads to stop after the correct answer is found?

RabidGorilla
  • 107
  • 2
  • 10
  • 1
    [This answer](http://stackoverflow.com/a/325528/677122) should help you find a way. – Midnighter May 27 '14 at 23:11
  • Generally the simplest design is to have the thread periodically check a flag to terminate which can be set by other threads. – aestrivex May 27 '14 at 23:16
  • 2
    A word of advice: Don't create a `Thread` for every line in the file, especially if there could be 1000000 lines in there. You should use a `multiprocessing.pool.ThreadPool` instead, so you limit yourself to some sane number of threads. – dano May 27 '14 at 23:16
  • ohh ya, actually that does make sense. Thanks!!! – RabidGorilla May 27 '14 at 23:16
  • Well there are not nearly that many lines in the file, I was just trying to make a point. – RabidGorilla May 27 '14 at 23:25

1 Answers1

0

Strangely in Python you can't kill threads:

Python’s Thread class supports a subset of the behavior of Java’s Thread class; currently, there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted.

https://docs.python.org/2/library/threading.html#threading.ThreadError

This sample creates a thread that will run for 10 seconds. The parent then waits a second, then is "done", and waits (ie: join()s) the outstanding threads before exiting cleanly.

import sys, threading, time

class MyThread(threading.Thread):
    def run(self):
        for _ in range(10):
            print 'ding'
            time.sleep(1)

MyThread().start()

time.sleep(2)

print 'joining threads'
for thread in threading.enumerate():
    if thread is not threading.current_thread():
        thread.join()
print 'done'
johntellsall
  • 14,394
  • 4
  • 46
  • 40