How to timeout when waiting for raw_input from user ?

zeph zephjc at gmail.com
Sat Dec 5 17:25:17 EST 2009


Here's what I came up with, though it only asks once question then
quits depending on the answer or lack thereof.  And while, yes, you
can't interrupt a raw_input call from a timer, providing for a blank
line (user hitting enter) is a way around it:

import threading import Timer
from random import randrange
import sys

def multiply_game():
  a = randrange(1,10)
  b = randrange(1,10)
  answer = raw_input('what is %s * %s?: ' % (a,b))
  if not answer:
	return
  timer.cancel()
  if str(answer) == str(a * b):
    print 'right! :D'
  else:
    print 'wrong :('

def tooslow():
  print "\ntoo slow :(\nHit ENTER to quit"

timer = Timer(30, tooslow)  # 30 seconds
timer.start()
multiply_game()



More information about the Python-list mailing list