如何在Python中实现限时用户输入?
Python 中的限时用户输入
当使用输入函数请求用户输入时,您可能希望限制用户的时间来回应。这使您可以优雅地处理超时并提供适当的反馈。
使用限时输入
要实现限时输入,请考虑以下方法:
阻塞线程方法(Python 2/3)
import threading timeout = 10 # In seconds t = threading.Timer(timeout, lambda: print('Sorry, times up.')) t.start() prompt = "You have {} seconds to choose the correct answer...\n".format(timeout) answer = input(prompt) t.cancel() # Stop the timer if the user provides a response
非阻塞线程方法(Python 3)
import sys import msvcrt # For Windows import time # For Unix 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(): # For Windows # Handle keyboard input else: # For Unix ready, _, _ = select.select([sys.stdin], [], [], timeout) if ready: return sys.stdin.readline().rstrip('\n') raise TimeoutExpired()
信号处理方法(类 Unix)系统)
import signal def alarm_handler(signum, frame): raise TimeoutExpired() def input_with_timeout(prompt, timeout): signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(timeout) try: return input(prompt) finally: signal.alarm(0) # Cancel the alarm
选择最适合您的操作系统和阻止要求的方法。
以上是如何在Python中实现限时用户输入?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Linux终端中查看Python版本时遇到权限问题的解决方法当你在Linux终端中尝试查看Python的版本时,输入python...

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

在使用Python的pandas库时,如何在两个结构不同的DataFrame之间进行整列复制是一个常见的问题。假设我们有两个Dat...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

Uvicorn是如何持续监听HTTP请求的?Uvicorn是一个基于ASGI的轻量级Web服务器,其核心功能之一便是监听HTTP请求并进�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...
