小编典典

Python-键盘输入是否超时?

python

你如何提示用户进行一些输入,但在N秒后超时?

Google指向http://mail.python.org/pipermail/python-list/2006-January/533215.html上与此有关的邮件线程,但似乎无法正常工作。无论是a sys.input.readline还是timer.sleep(),发生超时的语句总是可以得到:

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

不知何故,除了失败。


阅读 827

收藏
2020-02-09

共2个答案

小编典典

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

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
2020-02-09
小编典典

使用选择呼叫的时间更短,并且应该更便携

import sys, select

print "You have ten seconds to answer!"

i, o, e = select.select( [sys.stdin], [], [], 10 )

if (i):
  print "You said", sys.stdin.readline().strip()
else:
  print "You said nothing!"
2020-02-09