Non-Blocking Raw_input For Python

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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!]