Skip to content

Instantly share code, notes, and snippets.

@atupal
Created June 26, 2013 06:31
Show Gist options
  • Select an option

  • Save atupal/5865214 to your computer and use it in GitHub Desktop.

Select an option

Save atupal/5865214 to your computer and use it in GitHub Desktop.
python set time limit on input
import msvcrt
import time
def raw_input_with_timeout(prompt, timeout=30.0):
finishat = time.time() + timeout
result = []
while True:
if msvcrt.kbhit():
result.append(msvcrt.getche())
if result[-1] == '\r': # or \n, whatever Win returns;-)
return ''.join(result)
time.sleep(0.1) # just to yield to other processes/threads
else:
if time.time() > finishat:
return None
import thread
import threading
def raw_input_with_timeout(prompt, timeout=30.0):
print prompt,
timer = threading.Timer(timeout, thread.interrupt_main)
astring = None
try:
timer.start()
astring = raw_input(prompt)
except KeyboardInterrupt:
pass
timer.cancel()
return astring
@Varunhack
Copy link
Copy Markdown

You can use the library from https://pypi.org/project/inputimeout/

@TaokyleYT
Copy link
Copy Markdown

This cursed programs hurt my brain so much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment