Last active
January 10, 2025 18:04
-
-
Save joedf/879dc50449b7a8f2f60d7d858adbdd1e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| # -------------------------------------------------- | |
| # joedf: modified based on these examples: | |
| # - https://stackoverflow.com/a/47378376/883015 | |
| # - https://gist.github.com/jasonrdsouza/1901709 | |
| # -------------------------------------------------- | |
| def _sys_exit(): | |
| # sys.exit() | |
| # quit() | |
| raise KeyboardInterrupt | |
| # Find the right getch() and getKey() implementations | |
| try: | |
| # POSIX system: Create and return a getch that manipulates the tty | |
| import termios | |
| import sys, tty | |
| def getch(): | |
| fd = sys.stdin.fileno() | |
| old_settings = termios.tcgetattr(fd) | |
| try: | |
| tty.setraw(fd) | |
| ch = sys.stdin.read(1) | |
| finally: | |
| termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) | |
| return ch | |
| # Read arrow keys correctly | |
| def getKey(): | |
| firstChar = getch() | |
| if firstChar == '\x1b': | |
| return {"[A": "up", "[B": "down", "[C": "right", "[D": "left"}[getch() + getch()] | |
| else: | |
| val = ord(firstChar) | |
| if val in [3, 4, 26, 27]: | |
| _sys_exit() | |
| return firstChar, val | |
| except ImportError: | |
| # Non-POSIX: Return msvcrt's (Windows') getch | |
| from msvcrt import getch | |
| # Read arrow keys correctly | |
| def getKey(): | |
| firstChar = getch() | |
| if firstChar == b'\xe0' or firstChar == b'\x00': | |
| second = getch() | |
| return {"H": "up", "P": "down", "M": "right", "K": "left"}[second.decode("utf-8")], [firstChar, second] | |
| else: | |
| key = firstChar.decode("utf-8") | |
| val = ord(key) | |
| if val == 3: # handle ctrl+C | |
| _sys_exit() | |
| if key == ' ': | |
| key = "space" | |
| elif key == '\r': | |
| key = "enter" | |
| elif val == 8: | |
| key = "backspace" | |
| elif val == 9: | |
| key = "tab" | |
| elif val == 27: | |
| key = "esc" | |
| return key, val | |
| if __name__ == "__main__": | |
| while 1: | |
| d, c = getKey() | |
| # print(f'You pressed {d} ({ord(d)})') | |
| print(f'You pressed {d} ({c})') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment