Created
June 26, 2013 06:31
-
-
Save atupal/5865214 to your computer and use it in GitHub Desktop.
python set time limit on input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
You can use the library from https://pypi.org/project/inputimeout/