Last active
February 21, 2022 23:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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