键盘输入超时?

新手上路,请多包涵

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

Google 在 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

以某种方式 except 未能捕捉到。

原文由 pupeno 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 405
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

原文由 user137673 发布,翻译遵循 CC BY-SA 2.5 许可协议

使用 select 调用更短,而且应该更便携

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!"

原文由 Pontus 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏