带超时的键盘输入?
你想要让用户输入一些内容,但如果超过N秒就自动停止,这该怎么做呢?
在网上搜索时,谷歌给出的一个链接指向了一个邮件讨论串,地址是 http://mail.python.org/pipermail/python-list/2006-January/533215.html,不过看起来这个方法并不好用。在设置超时的那段代码中,无论是用 sys.input.readline
还是 timer.sleep()
,我总是会遇到:
<type 'exceptions.TypeError'>: [raw_]input expected at most 1 arguments, got 2
而且似乎这个异常处理没有起作用。
29 个回答
20
如果你不在乎它是怎么工作的,那就直接
pip install inputimeout
就行了。
from inputimeout import inputimeout, TimeoutOccurred
if __name__ == "__main__":
try:
c = inputimeout(prompt='hello\n', timeout=3)
except TimeoutOccurred:
c = 'timeout'
print(c)
124
使用选择调用(select call)会更简洁,而且应该更容易在不同的环境中使用。
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!"
51
你链接的这个例子是错误的,实际上异常发生在调用警报处理程序的时候,而不是在读取阻塞的时候。你可以试试这个:
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