Python-键盘输入是否超时?

发布于 2021-02-02 23:23:00

你如何提示用户进行一些输入,但在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

不知何故,除了失败。

关注者
0
被浏览
134
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

    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
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看