/ Snake / getkey.py
getkey.py
 1  import sys
 2  import termios
 3  import tty
 4  
 5  
 6  def getkey() -> str:
 7      def gk() -> str:
 8          fd: int = sys.stdin.fileno()
 9          old_settings = termios.tcgetattr(fd)
10          try:
11              tty.setraw(sys.stdin.fileno())
12              ch: str = sys.stdin.read(1)
13          finally:
14              termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
15          return ch
16  
17      out: str = gk()
18      if out == "\033":
19          o: str = gk()
20          if o == "[":
21              return out + o + gk()
22          return out + o
23      return out