Home > Backend Development > Python Tutorial > How Can I Implement Time-Limited User Input in Python?

How Can I Implement Time-Limited User Input in Python?

Barbara Streisand
Release: 2024-11-27 01:49:11
Original
368 people have browsed it

How Can I Implement Time-Limited User Input in Python?

Time-Limited User Input in Python

When soliciting user input with the input function, you may want to limit the time the user has to respond. This allows you to gracefully handle timeouts and provide appropriate feedback.

Using a Time-Limited Input

To implement time-limited input, consider the following approaches:

Blocking Thread Approach (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
Copy after login

Non-Blocking Thread Approach (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()
Copy after login

Signal Handling Approach (Unix-like systems)

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
Copy after login

Choose the approach that best suits your operating system and blocking requirements.

The above is the detailed content of How Can I Implement Time-Limited User Input in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template