Created
May 17, 2022 20:24
-
-
Save surajRathi/ef0de64e1aa7153fb5b99932815cea66 to your computer and use it in GitHub Desktop.
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 select | |
import sys | |
import time | |
if os.name == 'nt': | |
import msvcrt | |
else: | |
import tty | |
import termios | |
class GetKey: | |
def __init__(self): | |
self.is_nt = os.name == 'nt' | |
def __enter__(self): | |
if not self.is_nt: | |
self.settings = termios.tcgetattr(sys.stdin) | |
return self | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.settings) | |
def get_key(self) -> str: | |
if self.is_nt: | |
timeout = 0.1 | |
start_time = time.time() | |
while 1: | |
if msvcrt.kbhit(): | |
if sys.version_info[0] >= 3: | |
return msvcrt.getch().decode() | |
else: | |
return msvcrt.getch() | |
elif time.time() - start_time > timeout: | |
return '' | |
tty.setraw(sys.stdin.fileno()) | |
rlist, _, _ = select.select([sys.stdin], [], [], 0.1) | |
if rlist: | |
key = sys.stdin.read(1) | |
else: | |
key = '' | |
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.settings) | |
return key |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment