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

如何让定时器功能覆盖「输入值」提示,超时直接终止用户输入流程

问题根因
  • 初始版本逻辑完全错误:输入业务代码直接写在了倒计时循环的最前部,且执行完成后直接return返回,time.sleep(1)、倒计时计数递减、超时提醒的代码缩进错误,完全处于循环外,永远不会执行,自然没有超时限制效果。
  • 调整后的Timer版本仅实现了超时触发打印的逻辑,没有设计超时中断阻塞输入的机制,input()是系统级阻塞调用,普通的打印触发不会打断它的执行,因此流程还是会完整走完。
可行实现方案

可以通过线程超时+异常抛出的方式实现中断效果,以下是跨Windows、Linux可运行的代码:

import pandas as pd
import threading
import _thread

# 全局超时标记
is_timeout = False

def timeout_handler():
    global is_timeout
    is_timeout = True
    print("\n超时,流程中断!")
    # 抛出中断异常打断阻塞的input
    _thread.interrupt_main()

def get_input_with_timeout(prompt, timeout):
    try:
        return input(prompt)
    except KeyboardInterrupt:
        if is_timeout:
            # 超时触发的中断,直接退出
            exit()
        else:
            # 用户主动Ctrl+C的情况可自行扩展处理逻辑
            raise

if __name__ == "__main__":
    # 可自行调整总超时时间,单位秒
    total_timeout = 10
    # 启动超时计时器
    timer = threading.Timer(total_timeout, timeout_handler)
    timer.start()

    try:
        a = int(get_input_with_timeout("Enter number of instances: ", total_timeout))
        test3 = []
        i = 0
        while i < a:
            pl = int(get_input_with_timeout(f"Enter arbitrary integer ({i+1}/{a}): ", total_timeout))
            test3.append(pl)
            i += 1
        # 输入完成,主动取消计时器避免超时误触发
        timer.cancel()
        print("输入完成,生成DataFrame如下:")
        DF1 = pd.DataFrame(test3, columns=["输入值"])
        print(DF1)
    except ValueError:
        timer.cancel()
        print("输入值不是合法整数,流程退出")

代码说明

  • 超时触发时会调用_thread.interrupt_main()向主线程抛出KeyboardInterrupt异常,直接打断正在阻塞的input()调用
  • 输入所有内容完成后会主动取消计时器,避免超时误触发
  • 额外增加了非整数输入的异常捕获,避免程序崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:06:03