Python 3定时输入

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

我想做的是使用输入向用户提问。例如:

print('some scenario')
prompt = input("You have 10 seconds to choose the correct answer...\n")

然后如果时间到了,则打印类似

print('Sorry, times up.')

向我指出正确方向的任何帮助将不胜感激。

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

    这似乎可行:

    import time
    from threading import Thread
    
    answer = None
    
    def check():
        time.sleep(2)
        if answer != None:
            return
        print "Too Slow"
    
    Thread(target = check).start()
    
    answer = raw_input("Input something: ")
    


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

    如果在用户未提供答案时阻塞主线程是可以接受的:

    from threading import Timer
    
    timeout = 10
    t = Timer(timeout, print, ['Sorry, times up'])
    t.start()
    prompt = "You have %d seconds to choose the correct answer...\n" % timeout
    answer = input(prompt)
    t.cancel()
    

    否则,你可以在Windows(未经测试)上使用@Alex Martelli的答案(针对Python 3修改):

    import msvcrt
    import time
    
    class TimeoutExpired(Exception):
        pass
    
    def input_with_timeout(prompt, timeout, timer=time.monotonic):
        sys.stdout.write(prompt)
        sys.stdout.flush()
        endtime = timer() + timeout
        result = []
        while timer() < endtime:
            if msvcrt.kbhit():
                result.append(msvcrt.getwche()) #XXX can it block on multibyte characters?
                if result[-1] == '\n':   #XXX check what Windows returns here
                    return ''.join(result[:-1])
            time.sleep(0.04) # just to yield to other processes/threads
        raise TimeoutExpired
    

    用法:

    try:
        answer = input_with_timeout(prompt, 10)
    except TimeoutExpired:
        print('Sorry, times up')
    else:
        print('Got %r' % answer)
    

    在Unix上,你可以尝试:

    import select
    import sys
    
    def input_with_timeout(prompt, timeout):
        sys.stdout.write(prompt)
        sys.stdout.flush()
        ready, _, _ = select.select([sys.stdin], [],[], timeout)
        if ready:
            return sys.stdin.readline().rstrip('\n') # expect stdin to be line-buffered
        raise TimeoutExpired
    

    要么:

    import signal
    
    def alarm_handler(signum, frame):
        raise TimeoutExpired
    
    def input_with_timeout(prompt, timeout):
        # set signal handler
        signal.signal(signal.SIGALRM, alarm_handler)
        signal.alarm(timeout) # produce SIGALRM in `timeout` seconds
    
        try:
            return input(prompt)
        finally:
            signal.alarm(0) # cancel alarm
    


知识点
面圈网VIP题库

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

去下载看看