You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python打字速度测试程序如何实现输入循环指定时长后自动终止

核心问题

  • Python内置input()是阻塞式调用,触发后会一直等待用户输入完成才会执行后续逻辑,因此原代码里的时间判断只有在用户每次输入完成后才会运行,计时到期时如果还卡在输入环节,循环自然不会停止。

可行实现方案(全平台兼容)

通过多线程分离计时逻辑和输入逻辑,计时结束后主动中断阻塞的输入操作即可,完整代码如下:

from datetime import datetime, timedelta
import threading
import os

text = '你好,我叫马修'
time_up = False

def count_down(duration):
    global time_up
    end_time = datetime.now() + timedelta(seconds=duration)
    while datetime.now() < end_time:
        pass
    time_up = True
    # 不同平台发送中断信号终止输入
    if os.name == 'nt':
        import ctypes
        ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, 0)
    else:
        import signal
        os.kill(os.getpid(), signal.SIGINT)

def typing_test(duration):
    # 启动计时守护线程
    threading.Thread(target=count_down, args=(duration,), daemon=True).start()
    while not time_up:
        try:
            answer = input('请输入以下文本:' + text + '\n\n')
            # 此处可补充打字正确率、速度统计逻辑
        except KeyboardInterrupt:
            if time_up:
                print("\n计时结束,测试终止")
                break

if __name__ == "__main__":
    duration = int(input('请输入测试时长(秒):'))
    typing_test(duration)

逻辑说明

  • 计时逻辑单独放在子线程运行,不会被输入操作阻塞
  • 计时到期后主动给主进程发中断信号,强制跳出input()的阻塞状态
  • 捕获中断信号后判断是否为计时到期触发,是则直接终止测试流程

内容的提问来源于stack exchange,提问作者Matthew Doig

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 11:15:05