python - 如何将有限的输入时间添加到我的代码中?
问题描述
我一直在尝试为 Python 脚本找到一个好的有限输入时间代码,我终于得到了一个可以工作的代码:
from threading import Timer
timeout = 5
t = Timer(timeout, print, ["Time's up!"])
t.start()
entry = input('> ')
t.cancel()
但是,我需要能够在计时器结束时运行一个函数。另外-我希望在计时器代码内部调用该函数-否则,如果您在计时器用完之前键入条目,则无论如何仍会调用该函数。任何人都可以编辑这段代码我必须能够在计时器结束时运行一个函数吗?
解决方案
如果您在用户没有提供任何答案时阻塞主线程很好,那么您共享的上述代码可能会起作用。
否则,您可以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
推荐阅读
- java - Restful 系统调用类字段成员与后端类字段类型不同
- javascript - vuetify v-data-table 不显示嵌套对象数据
- android - 在 Android Studio 3.6 中使用 Import Sceneform Asset 导入 FBX 时出错
- powershell - 如何使用powershell将文件输入可执行文件?
- angular - 如何以角度为子组件的子组件指定路由?
- db2 - DB2 on Cloud 中的高可用性特性
- laravel - 列的工厂相同 ID,自动增量,Laravel
- primefaces - 如何使用 ap:dataTable 和 p:columnGroup 标题使用 p:columns
- talend - 使用 Talend 从 Google Drive 读取文件
- r - 从 R 中的数值列向量创建一个因子