Home > Backend Development > Python Tutorial > How Can I Get Asynchronous Keyboard Input with a Timeout in Python?

How Can I Get Asynchronous Keyboard Input with a Timeout in Python?

Mary-Kate Olsen
Release: 2024-12-28 09:58:11
Original
631 people have browsed it

How Can I Get Asynchronous Keyboard Input with a Timeout in Python?

Asynchronous Keyboard Input with Timeout Handling

The task at hand is to solicit user input while imposing a timeout to prevent indefinite waiting. While Google suggests a mailing thread for this, it may not yield satisfactory results.

The challenge arises from the system input function ([raw_]input) accepting at most one argument. However, to implement a timeout, one must pass a timeout parameter. This results in a TypeError.

Solution using Select Poll

A more reliable solution involves using the select.select() system call:

import sys, select

print("You have ten seconds to answer!")

i, o, e = select.select([sys.stdin], [], [], 10)

if (i):
    print("You said", sys.stdin.readline().strip())
else:
    print("You said nothing!")
Copy after login

Breakdown

  • select.select() registers sys.stdin for input polling with a timeout of 10 seconds.
  • The i variable contains a list of input-ready file descriptors, indicating if there was user input.
  • If input is present, the readline() method is used to retrieve it.
  • If the timeout expires without input, the "You said nothing!" message is displayed.

This approach offers greater portability and efficiency in handling keyboard input with timeout functionality.

The above is the detailed content of How Can I Get Asynchronous Keyboard Input with a Timeout 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