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
不知何故,除了失败。
回答:
你链接到的示例是错误的,并且异常实际上是在调用警报处理程序而不是读取块时发生的。最好试试这个:
import signalTIMEOUT = 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
以上是 Python-键盘输入是否超时? 的全部内容, 来源链接: utcz.com/qa/428405.html