473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Need function like "raw_input", but with time limit

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?
Jul 18 '05 #1
4 7663
Radioactive Man <rm@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 select.select with
sys.stdin.fileno as the only file descriptor of interest and whatever
timeout you wish. Depending on what select.select 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, select.select 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.
Alex

Jul 18 '05 #2
"Radioactive Man" <rm@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)


this works on some platforms:

import signal, sys

def alarm_handler(*args):
raise Exception("timeout")

def function_xyz(prompt, timeout):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
sys.stdout.write(prompt)
sys.stdout.flush()
try:
text = sys.stdin.readline()
except:
text = ""
signal.alarm(0)
return text

</F>

Jul 18 '05 #3
On Sun, 19 Sep 2004 11:21:49 +0200, al*****@yahoo.com (Alex Martelli)
wrote:
Radioactive Man <rm@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 select.select with
sys.stdin.fileno as the only file descriptor of interest and whatever
timeout you wish. Depending on what select.select 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, select.select 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.


In other words, the user must make any entries while the time.sleep()
statement is running. If the user has entered data during this time,
it should be indicated by the value of msvcrt.kbhit(). The problem
I've had is that msvcrt.kbhit() returns 0 no matter what I've entered
before the statement is executed and while the sleep statement is
being executed.

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.
Alex

Thanks for the info.
Jul 18 '05 #4
On Sun, 19 Sep 2004 12:00:09 +0200, "Fredrik Lundh"
<fr*****@pythonware.com> wrote:
"Radioactive Man" <rm@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)


this works on some platforms:

import signal, sys

def alarm_handler(*args):
raise Exception("timeout")

def function_xyz(prompt, timeout):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
sys.stdout.write(prompt)
sys.stdout.flush()
try:
text = sys.stdin.readline()
except:
text = ""
signal.alarm(0)
return text

</F>


Is that for a Unix system? I am running windows 95 and/or XP and my
signal.signal module does not have a "SIGALRM" attribute. Thus, I get
an error message when I try to run that script.

Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
by: zhi | last post by:
Really confused, when I use keyword style argument as following: >>> input(prompt="hello") Traceback (most recent call last): File "<pyshell#52>", line 1, in -toplevel- input(prompt="hello")...
2
by: User | last post by:
Anyone know of a function like raw_input(), but with a built-in or user-specified time limit? Ideally, it would return an empty string ('') and resume processing if the user didn't enter something...
8
by: b83503104 | last post by:
Hi, I want to accept the user's answer yes or no. If I do this: answer = input('y or n?') and type y on the keyboard, python complains Traceback (most recent call last):
1
by: JerryKreps | last post by:
Hi, folks -- I'm a Python pup. As you can see from the session copied at the end of this post, I have the latest version of Python, and I've been using the Editor-Shell of the latest version of...
5
by: iminal | last post by:
I am trying to make a very simple program and am very new to the whole programming thing. my program is supposed to ask a user for any time in the for format XX:XX:XX and then ask for a time...
13
by: darthbob88 | last post by:
Problem: I wish to run an infinite loop and initialize a variable on each iteration. Sort of like, "Enter Data", test it, "No good!", "Next Try?", test it, etc. What I've tried is simply while 1:...
10
by: wd.jonsson | last post by:
Hmm, my while loop with "or" doesn't seem to work as I want it to... How do I tell the while loop to only accept "Y" or "y" or "N" or "n" input from the str(raw_input)? Thank's in advance! ...
3
by: shing | last post by:
Can someone tell me what are the errors in my line of code? I am new to Python and so you will have to try and ignore my noobishness, Sorry. ...
10
by: jonathanemil | last post by:
Hello, I am a 1st semester Computer Science student in a Python class. Our current assignment calls for us to read a list from a file, create a 2-dimensional list from the file, and check to see...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.