How can I wait for user to press any key for 20 secs? I.e. I show the message and it counts 20 secs, the code continues execution either if 20 secs are passed OR if user pressed any key. How can I do it with python?
If you're on Windows:
def wait_for_user(secs):
import msvcrt
import time
start = time.time()
while True:
if msvcrt.kbhit():
msvcrt.getch()
break
if time.time() - start > secs:
break
One possible solution is to use select
to check the values, but I don't like it, I feel like I'm wasting my time.
On the other hand you can use signaling on Linux systems to handle the problem. after a certain amount of time, a exception will be raised, try
fails and code continues in except
:
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 ''
The code has been taken from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With