Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > How to timeout when waiting for raw_input from user ?

Thread Tools

How to timeout when waiting for raw_input from user ?

Posts: n/a
Try using the function timelimited from this recipe


An (untested) example with a 60 second timeout would be:

r = timelimited(60, raw_input, 'enter right or wrong: ')
except TimeLimitExpired:
except KeyboardInterrupt:


On Dec 4, 3:52*pm, northof40 <(E-Mail Removed)> wrote:
> Hi - I'm writing a *very* simple program for my kids. It asks the user
> to give it the answer to a maths question and says "right" or "wrong"
> They now want a timed version where they would only get so long to
> respond to the question.
> I'm thinking of some logic where a raw_input call is executed and then
> if more than X seconds elapses before the prompt is replied to the
> process writes a message "Sorry too slow" (or similar).
> I can't see the wood for the trees here - what's the best way to do
> this given the rather simple environment it's needed within.
> Regards
> richard.

Reply With Quote
Posts: n/a
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:
if str(answer) == str(a * b):
print 'right! '
print 'wrong '

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

timer = Timer(30, tooslow) # 30 seconds
Reply With Quote
Rune Strand
Posts: n/a
On Dec 5, 3:42*pm, Maxim Khitrov <(E-Mail Removed)> wrote:

> I'm not talking about the Timer, I'm talking about the original
> question. There's nothing (that I know of) you can do with a Timer on
> Windows to interrupt a raw_input call.

That is true. But if the issue here is to present a question, and
await answer for N seconds, before pusing next question, Timer() can
be used to call SendKeys() and have it send "{ENTER}" to raw_input.

SendKeys is Win-only
Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How include a large array? Edward A. Falk C Programming 1 04-04-2013 08:07 PM
using input(), raw_input() to allow user to run different functions Python 3 06-30-2009 04:01 PM
Timeout waiting for an answer in TCPClient QDL ASP .Net 0 12-13-2006 10:20 AM
"Timeout while waiting for connection" caocheng C++ 0 04-09-2006 02:35 AM
Timeout::timeout and Socket timeout Mark Probert Ruby 1 10-06-2004 09:30 AM