Python - do something until keypress or timeout

Viewed 8971

I've nearly solved this problem but I think I need a nudge in the right direction.

I want to do something every five seconds until either a certain amount of time has elapsed or the user interrupts it (in which case it finishes that iteration of the loop before finishing).

import time
import threading

def do_something():
    T0 = time.clock()
    while (time.clock() - T0) < 60 and not e.isSet(): #as long as 60s haven't elapsed
                                                      #and the flag is not set
        #here do a bunch of stuff
        time.sleep(5)

thread = threading.Thread(target=do_something, args=())
thread.start()
e = threading.Event()

while thread.isAlive():
    #here I want the main thread to wait for a keypress and, if it receives it,
    #set the event e, which will cause the thread to finish its work.

I can't work out how to make that last line work. Using raw_input() inside the loop will block until the user hits enter whether the thread finishes its work or not. Is there another module that will do what I want?

Edit: I am using Windows XP.

3 Answers
Related