Skip to content

Instantly share code, notes, and snippets.

@zmwangx
Last active February 21, 2022 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmwangx/3739bd6abd8a2c05cbdbbc2077165509 to your computer and use it in GitHub Desktop.
Save zmwangx/3739bd6abd8a2c05cbdbbc2077165509 to your computer and use it in GitHub Desktop.
Python: cross-platform code to read keypress with a timeout. Good for "press any key to continue" with an expiration timer.
import os
import time
from typing import Optional
if os.name == "posix":
import select
import sys
import termios
import tty
def read_keypress_with_timeout(timeout: float) -> Optional[str]:
end_time = time.time() + timeout
stdin_fileno = sys.stdin.fileno()
saved_tcattr = termios.tcgetattr(stdin_fileno)
try:
tty.setcbreak(stdin_fileno)
while time.time() <= end_time:
if select.select((sys.stdin,), (), (), 0.1)[0]:
return sys.stdin.read(1)
finally:
termios.tcsetattr(stdin_fileno, termios.TCSAFLUSH, saved_tcattr)
elif os.name == "nt":
try:
import msvcrt
def read_keypress_with_timeout(timeout: float) -> Optional[str]:
end_time = time.time() + timeout
while time.time() <= end_time:
if msvcrt.kbhit():
return msvcrt.getwch()
except ImportError:
def read_keypress_with_timeout(timeout: float) -> None:
time.sleep(timeout)
else:
def read_keypress_with_timeout(timeout: float) -> None:
time.sleep(timeout)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment