键盘输入超时? [英] Keyboard input with timeout?

查看:70
本文介绍了键盘输入超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何提示用户输入但在 N 秒后超时?

How would you prompt the user for some input but timing out after N seconds?

Google 在 http://mail.python.org/pipermail/python-list/2006-January/533215.html 但它似乎不起作用.发生超时的语句,不管是sys.input.readline还是timer.sleep(),我总是得到:

Google is pointing to a mail thread about it at http://mail.python.org/pipermail/python-list/2006-January/533215.html but it seems not to work. The statement in which the timeout happens, no matter whether it is a sys.input.readline or timer.sleep(), I always get:

<type 'exceptions.TypeError'>: [raw_]input expected at most 1 arguments, got 2

以某种方式,except 未能捕获.

which somehow the except fails to catch.

推荐答案

您链接到的示例是错误的,实际上是在调用警报处理程序而不是读取块时发生异常.最好试试这个:

The example you have linked to is wrong and the exception is actually occuring when calling alarm handler instead of when read blocks. Better try this:

import signal
TIMEOUT = 5 # number of seconds your want for timeout

def interrupted(signum, frame):
    "called when read times out"
    print 'interrupted!'
signal.signal(signal.SIGALRM, interrupted)

def input():
    try:
            print 'You have 5 seconds to type in your stuff...'
            foo = raw_input()
            return foo
    except:
            # timeout
            return

# set alarm
signal.alarm(TIMEOUT)
s = input()
# disable the alarm after success
signal.alarm(0)
print 'You typed', s

这篇关于键盘输入超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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