Python等待x秒键,如果没有按下则继续执行 [英] Python wait x secs for a key and continue execution if not pressed

查看:39
本文介绍了Python等待x秒键,如果没有按下则继续执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 python 的 n00b,我正在寻找执行以下操作的代码片段/示例:

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

  • 显示类似按任意键配置或等待 X 秒继续"之类的消息
  • 例如,等待 5 秒并继续执行,或者在按下某个键时进入 configure() 子例程.

感谢您的帮助!

伊万·詹森斯

推荐答案

如果您使用的是 Unix/Linux,那么 select 模块会帮助你.

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

如果您使用的是 Windows,请查看 msvcrt 模块.(注意这在 IDLE 中不起作用,但在 cmd 提示符下有效)

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

这篇关于Python等待x秒键,如果没有按下则继续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆