Need function like "raw_input", but with time limit

Alex Martelli aleaxit at
Sun Sep 19 11:21:49 CEST 2004

Radioactive Man <rm at rm.rm> wrote:

> anyone know of a function like "raw_input", which collects a string
> from the user entry, but one where I can set a time limit, as follows:
> time_limit = 10    # seconds
> user_answer = function_xyz("GIVE ME AN ANSWER:  ", time_limit)  
> The problem with "raw_input" is that it will stop unattended script
> indefinitely.  I'm looking for a function that does the exact same
> thing, but with a time limit feature, and preferably one that returns
> an empty string ('') when it gets no response.  Any suggestions?

It depends on what platforms you need to run on.  On any kind of
Unix-like platform (including Linux, BSD, MacOSX, ...), the function
select of module select can work on any kind of files, including
sys.stdin, and it does provide timeout functionality, too.  So, you
could sys.stdout.write the prompt, then call with
sys.stdin.fileno as the only file descriptor of interest and whatever
timeout you wish.  Depending on what returns you can then
either sys.stdin.readline (and strip the trailing \n) or just return the
empty string from your function.

Unfortunately, on Windows, works only on sockets, not
ordinary files nor the console.  So, if you want to run on Windows, you
need a different approach.  On Windows only, the Python standard library
has a small module named msvcrt, including functions such as
msvcrt.kbhit which tells you whether any keystroke is waiting to be
read.  Here, you might sys.stdout.write the prompt, then enter a small
loop (including a time.sleep(0.2) or so) which waits to see whether the
user is pressing any key -- if so then you can sys.stdin.readline etc,
but if after your desired timeout is over no key has been hit, then just
return the empty string from your function.

All of this assumes that if the user has STARTED typing something then
you want to wait indefinitely (not timeout in the middle of their
entering their answer!).  Otherwise, you have more work to do, since you
must ensure that the user has hit a Return (which means you must peek at
exactly what's in sys.stdin, resp. use msvcrt.getch, one character at a
time).  Fortunately, the slightly simpler approach of waiting
indefinitely if the user has started entering seems to be the preferable
one from a user interface viewpoint -- it lets you deal with unattended
consoles as you desire, yet IF the user is around at all it gives the
user all the time they want to COMPLETE their answer.


More information about the Python-list mailing list