How to Implement Time-Limited User Input in Python Using `raw_input()`?

Patricia Arquette
Release: 2024-11-19 16:35:02
Original
771 people have browsed it

How to Implement Time-Limited User Input in Python Using `raw_input()`?

Time-Limited User Input with Raw Input

In Python, the raw_input() function can be used to prompt the user for input. However, there may be scenarios where you want to limit the waiting time for user input to avoid indefinitely holding up the program.

Solution Using Threading Timer

For cross-platform and Windows-specific solutions, you can utilize threading.Timer from the threading module. Import the necessary modules:

import thread
import threading
Copy after login

Define a function called raw_input_with_timeout:

def raw_input_with_timeout(prompt, timeout=30.0):
    print(prompt, end=' ')    
    timer = threading.Timer(timeout, thread.interrupt_main)
    astring = None
    try:
        timer.start()
        astring = input(prompt)
    except KeyboardInterrupt:
        pass
    timer.cancel()
    return astring
Copy after login

This function prints the prompt, starts a timer, and prompts for user input using input. If the user takes longer than the specified timeout to input, the timer interrupts the main thread, causing a KeyboardInterrupt exception to be raised. The timer is canceled to prevent further interruptions.

If the input times out, it will return None. If the user provides input before the timeout, it will return the inputted string.

Note:

  • To distinguish between timeouts and user-initiated interruptions (e.g., if the user presses Ctrl C), you can save an indication of whether the interrupt was caused by a timeout in a global variable or use try/except to handle the KeyboardInterrupt exception and set a flag accordingly.
  • This approach does not work on Windows for 'normal files' like stdin. For a Windows-specific implementation, consider polling msvcrt.kbhit and msvcrt.getche in a loop while checking for timeouts.

The above is the detailed content of How to Implement Time-Limited User Input in Python Using `raw_input()`?. 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