【问题标题】:How to wait for 20 secs for user to press any key?如何等待 20 秒让用户按下任意键?
【发布时间】:2012-08-02 18:51:29
【问题描述】:

如何等待用户按任意键 20 秒? IE。我显示消息并计算 20 秒,如果超过 20 秒或用户按下任何键,代码将继续执行。我如何用python做到这一点?

【问题讨论】:

  • 查找非阻塞输入,然后在一个 while 循环中实现,检查当前时间与开始时间的比较。
  • @Lanaru:为什么要使用 while 循环?听起来像是忙着等待的糟糕案例。像select() 这样带有超时的东西可以做同样的事情。
  • 按任意键不等于输入任意字符串
  • 我确实看到了使用 pygame 的跨平台答案.. 但必须有更好的方法。

标签: python python-2.5


【解决方案1】:

如果您使用的是 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

【讨论】:

  • 这有点小气,但如果有人在睡觉的时候打到一个角色,你就无缘无故地等待。最好比较时间而不是睡眠。
【解决方案2】:

一种可能的解决方案是使用select 来检查值,但我不喜欢它,我觉得我在浪费时间。
另一方面,您可以在 Linux 系统上使用信号来处理问题。一定时间后,将引发异常,try 失败,代码在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 ''

代码取自here

【讨论】:

  • 另外,在您的特殊情况下,它还有另一个陷阱,即 raw_input 等待您最后输入 \n,因为 Python 默认处于行缓冲模式。
【解决方案3】:

(警告:未经测试的代码)

类似:

 import sys
 import select

 rlist, _, _ = select.select([sys.stdin], [], [], timeout=20)
 if len(rlist) == 0:
     print "user didnt input anything within 20 secs"
 else:
     print "user input something within 20 secs. Now you just have to read it"

编辑见:http://docs.python.org/library/select.html

【讨论】:

  • 我不知道选择模块,这很好知道。我只是在windows上测试了它,它没有工作。来自文档:注意:Windows 上的文件对象是不可接受的,但套接字是。在 Windows 上,底层的 select() 函数由 WinSock 库提供,不处理并非源自 WinSock 的文件描述符。
  • @BrendenBrown:哇,我不知道。感谢您的更新(这进一步加深了我对 Windows 开发的困惑……)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-15
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多