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

前端 未结 4 881
误落风尘
误落风尘 2020-12-09 20:31

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 secon
4条回答
  •  一整个雨季
    2020-12-09 21:15

    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...

提交回复
热议问题