Python wait x secs for a key and continue executio

2019-01-23 19:50发布

I'm a n00b to python, and I'm looking a code snippet/sample which performs the following:

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

Thank you for your help!

Yvan Janssens

标签: python wait
3条回答
啃猪蹄的小仙女
2楼-- · 2019-01-23 20:10

If you combine time.sleep, threading.Thread, and sys.stdin.read you can easily wait for a specified amount of time for input and then continue.

t = threading.Thread(target=sys.stdin.read(1) args=(1,))
t.start()
time.sleep(5)
t.join()
查看更多
Root(大扎)
3楼-- · 2019-01-23 20:13

Python doesn't have any standard way to catch this, it gets keyboard input only through input() and raw_input().

If you really want this you could use Tkinter or pygame to catch the keystrokes as "events". There are also some platform-specific solutions like pyHook. But if it's not absolutely vital to your program, I suggest you make it work another way.

查看更多
等我变得足够好
4楼-- · 2019-01-23 20:29

If you're on Unix/Linux then the select module will help you.

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're on Windows, then look into the msvcrt module. (Note this doesn't work in IDLE, but will in 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..."

Edit Changed the code samples so you could tell whether there was a timeout or a keypress...

查看更多
登录 后发表回答