If you just need something that can count while the user enters input, you can use a thread:
from threading import Thread,Event
from time import sleep
class Counter(Thread):
def __init__(self):
Thread.__init__(self)
self.count = 0
self._stop = Event()
def run(self):
while not self._stop.is_set():
sleep(1)
self.count+=1
def stop(self):
self._stop.set()
count = Counter()
# here we create a thread that counts from 0 to infinity(ish)
count.start()
# raw_input is blocking, so this will halt the main thread until the user presses enter
raw_input("taking input")
# stop and read the counter
count.stop()
print "User took %d seconds to enter input"%count.count
If you want to stop the raw_input
after n
seconds if no input has been entered by the user, then this is slightly more complicated. The most straight forward way to do this is probably using select
(although not if you are on a Windows machine). For examples, see:
raw_input and timeout
and
http://repolinux.wordpress.com/2012/10/09/non-blocking-read-from-stdin-in-python/