有时间限制的输入
在编程中,对用户输入施加时间限制是有益的。例如,您可能希望向用户询问问题并为他们提供有限的响应时间,例如:
print('some scenario') prompt = input("You have 10 seconds to choose the correct answer...\n")
如果用户超过时间限制,您可以显示类似以下的消息:
print('Sorry, times up.')
限时输入解决方案
实现限时输入,考虑以下选项:
from threading import Timer timeout = 10 t = Timer(timeout, print, ['Sorry, times up']) t.start() prompt = "You have %d seconds to choose the correct answer...\n" % timeout answer = input(prompt) t.cancel()
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] == '\r': return ''.join(result[:-1]) time.sleep(0.04) # just to yield to other processes/threads raise TimeoutExpired
import select import sys def input_with_timeout(prompt, timeout): sys.stdout.write(prompt) sys.stdout.flush() ready, _, _ = select.select([sys.stdin], [],[], timeout) if ready: return sys.stdin.readline().rstrip('\n') # expect stdin to be line-buffered raise TimeoutExpired
import signal def alarm_handler(signum, frame): raise TimeoutExpired def input_with_timeout(prompt, timeout): # set signal handler signal.signal(signal.SIGALRM, alarm_handler) signal.alarm(timeout) # produce SIGALRM in `timeout` seconds try: return input(prompt) finally: signal.alarm(0) # cancel alarm
通过实现这些方法,您可以有效地对用户输入应用时间限制,增强用户体验并控制程序流程。
以上是如何在编程中实现限时用户输入?的详细内容。更多信息请关注PHP中文网其他相关文章!