首页 > 解决方案 > 如何将有限的输入时间添加到我的代码中?

问题描述

我一直在尝试为 Python 脚本找到一个好的有限输入时间代码,我终于得到了一个可以工作的代码:

from threading import Timer

timeout = 5
t = Timer(timeout, print, ["Time's up!"])
t.start()
entry = input('> ')
t.cancel()

但是,我需要能够在计时器结束时运行一个函数。另外-我希望在计时器代码内部调用该函数-否则,如果您在计时器用完之前键入条目,则无论如何仍会调用该函数。任何人都可以编辑这段代码我必须能够在计时器结束时运行一个函数吗?

标签: python

解决方案


如果您在用户没有提供任何答案时阻塞主线程很好,那么您共享的上述代码可能会起作用。

否则,您可以msvcrt在以下意义上使用:

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

上述代码符合 Python3,您需要对其进行测试。

从 Python 文档阅读 https://docs.python.org/3/library/threading.html#timer-objects

我想出了以下可能有效的片段(尝试在命令行提示符下运行)

from threading import Timer


def input_with_timeout(x):    

def time_up():
    answer= None
    print('time up...')

t = Timer(x,time_up) # x is amount of time in seconds
t.start()
try:
    answer = input("enter answer : ")
except Exception:
    print('pass\n')
    answer = None

if answer != True:   # it means if variable has something 
    t.cancel()       # time_up will not execute(so, no skip)

input_with_timeout(5) # try this for five seconds

推荐阅读