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

如何为Python的input输入功能添加超时计时器?

实现input输入超时功能

Python标准库的input是阻塞调用,默认没有超时参数,这里提供两种可直接运行的实现方案:

方案1:信号量实现(仅支持Unix/Linux/macOS)

基于signal模块的系统信号实现,代码更简洁:

import signal

# 超时回调函数
def timeout_handler(signum, frame):
    print("\n输入超时,程序退出")
    exit()

# 绑定超时信号,设置5秒超时
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(5)

try:
    a = input('Stack Overflow is cool: ')
    # 输入完成后取消超时信号
    signal.alarm(0)
except KeyboardInterrupt:
    print("\n手动中断程序")
    exit()

if a == 'yes':
    print('Harold882')
else:
    print('asdf')

方案2:多线程实现(全平台通用)

兼容Windows、Linux、macOS全系统,适用场景更广:

import threading
import sys

# 存储用户输入的全局变量
user_input = None

def input_thread():
    global user_input
    user_input = input('Stack Overflow is cool: ')

# 启动守护线程处理输入,主程序退出时线程会自动销毁
t = threading.Thread(target=input_thread, daemon=True)
t.start()

# 等待输入最多5秒
t.join(timeout=5)

if user_input is None:
    print("\n输入超时,程序退出")
    sys.exit()

if user_input == 'yes':
    print('Harold882')
else:
    print('asdf')
通用计时器实现

可以用装饰器封装通用超时逻辑,给任意函数添加超时限制,无需修改原函数代码:

import threading
import functools
import time

def timeout(seconds):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = [None]
            # 自定义超时异常
            class TimeoutError(Exception):
                pass

            def target():
                try:
                    result[0] = func(*args, **kwargs)
                except Exception as e:
                    result[0] = e

            t = threading.Thread(target=target, daemon=True)
            t.start()
            t.join(seconds)
            if t.is_alive():
                raise TimeoutError(f"执行超时,限制时长为{seconds}秒")
            if isinstance(result[0], Exception):
                raise result[0]
            return result[0]
        return wrapper
    return decorator

# 使用示例:给测试函数设置3秒超时
@timeout(3)
def test_func():
    time.sleep(5)
    return "执行完成"

try:
    print(test_func())
except Exception as e:
    print(e)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:24:01