0

I am making a simple math test for my friend's class. The students will only have 45 seconds to solve each answer. Is there a way to make a timer that will count at the same time as the rest of the code runs and when it reaches 45 stops?

The test looks like this:

test = raw_input("How much is 62x5-23?")
if test == '287':
    print "Well done!"
djot
  • 2,952
  • 4
  • 19
  • 28
Vagozino
  • 73
  • 1
  • 5
  • this may help http://stackoverflow.com/questions/18950092/using-countdown-timer-to-jump-out-of-while-loop-python – Joe T Oct 13 '13 at 17:02
  • Hope this helps: http://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds – Aswin Murugesh Oct 13 '13 at 17:06

1 Answers1

0

Here's some code I used once (lifted off some page on the web which is now in the hands of a domain squatter, so no credit where credit is due, sadly):

import signal

class TimeoutException(Exception):
    pass

def timeout(timeout_time, default = None):
    def timeout_function(f):
        def f2(*args, **kwargs):
            def timeout_handler(signum, frame):
                raise TimeoutException()

            old_handler = signal.signal(signal.SIGALRM, timeout_handler)
            signal.alarm(timeout_time) # triger alarm in timeout_time seconds
            try:
                retval = f(*args, **kwargs)
            except TimeoutException, e:
                if default == None:
                    raise e
                return default
            finally:
                signal.signal(signal.SIGALRM, old_handler)
            signal.alarm(0)
            return retval
        return f2
    return timeout_function

# use like this:
@timeout(45)
def run():
    test = raw_input("How much is 62x5-23? ")
    if test == '287':
        print "Well done!"

# alternatively, pass a value that will be returned when the timeout is reached:
@timeout(45, False)
def run2():
    test = raw_input("How much is 62x5-23? ")
    if test == '287':
        print "Well done!"

if __name__ == '__main__':
    try:
        run()
    except TimeoutException:
        print "\nSorry, you took too long."

    # alternative call:
    if run2() == False:
        print "\nSorry, you took too long."

EDIT: probably works on Unix-type OS'es only.

robertklep
  • 198,204
  • 35
  • 394
  • 381