I needed a way to allow a raw_input() call to time out. In case it's useful to anyone, I wrote this solution which works under Unix-like OS's.
Simply call nonBlockingRawInput("your prompt text", n) where n is the number of seconds you would like the prompt to wait until it times out. If it does time out, it will return with an empty string.
import signal class AlarmException(Exception): pass def alarmHandler(signum, frame): raise AlarmException def nonBlockingRawInput(prompt='', timeout=20): signal.signal(signal.SIGALRM, alarmHandler) signal.alarm(timeout) try: text = raw_input(prompt) signal.alarm(0) return text except AlarmException: print '\nPrompt timeout. Continuing...' signal.signal(signal.SIGALRM, signal.SIG_IGN) return ''
[Edited Aug. 30, 2010 to fix a typo in the function name and generally improve formatting]
[Edited Feb 1, 2022 to add a tad more explanation, since the comments indicate people are still finding this!]
typo error: nonBockingRawInput x nonBlockingRawInput
I also think that signal.alarm(0) is wrong. I needed to comment it in order to make it work.
Posted by: Juanjo | August 27, 2010 at 09:07 AM
Thanks for pointing out the typo in the function name.
But I don't know what to make of your comment about alarm(0). That's there to cancel the alarm once you've typed something in. It works under the Python versions I've tried. (Though note: as my post says at the top, this is only for unix-like OS's.)
See the example in the Python docs at the end of this page: http://docs.python.org/library/signal.html.
Anyone else have any experiences, pro-or-con, on that issue?
Also, if anyone has a version that works for Windows, I'd appreciate hearing about it!
Posted by: Gary Robinson | August 30, 2010 at 11:04 AM
Thats' really good stuff.
I have been searching for this for a while. Other recivpies, like http://code.activestate.com/recipes/134892/ are far more ugly!
Best,
Heinrich
Posted by: Heinrich | September 18, 2012 at 08:44 PM
Thanks, this code has come in handy for me several times!! Too bad it's not cross-platform...
Posted by: Python for beginners | June 10, 2019 at 06:13 PM
Thanks for this post.
I use it now in a script where this problem bothered me for a long time.
Works on my debian 11 system with Python2.7 and Python 3.9, glad to have found it.
Best regards
Hellmut
Posted by: Hellmut Weber | January 13, 2022 at 05:41 AM