Python wait x secs for key and continue execution if not pressed

I am n00b for python and I am looking for a piece of code / sample that does the following:

  • Display a message such as "Press any key to configure or wait X seconds to continue"
  • Wait, for example, 5 seconds and continue execution, or enter the configure () routine if a key is pressed.

Thank you for your help!

Ivan Janssens

+5
source share
3 answers

If you are running Unix / Linux, select will help .

import sys
from select import select

print "Press any key to configure or wait 5 seconds..."
timeout = 5
rlist, wlist, xlist = select([sys.stdin], [], [], timeout)

if rlist:
    print "Config selected..."
else:
    print "Timed out..."

If you are on Windows, take a look at the msvcrt module . (Note that this does not work in IDLE, but will be at the cmd prompt)

import sys, time, msvcrt

timeout = 5
startTime = time.time()
inp = None

print "Press any key to configure or wait 5 seconds... "
while True:
    if msvcrt.kbhit():
        inp = msvcrt.getch()
        break
    elif time.time() - startTime > timeout:
        break

if inp:
    print "Config selected..."
else:
    print "Timed out..."

, , - ...

+16

Python , input() raw_input().

, Tkinter pygame, "". , pyHook. , -.

0

time.sleep, threading.Thread sys.stdin.read, .

t = threading.Thread(target=sys.stdin.read(1) args=(1,))
t.start()
time.sleep(5)
t.join()
0

All Articles