Skip to content

Instantly share code, notes, and snippets.

@appcove
Created August 16, 2020 04:00
Show Gist options
  • Save appcove/04019a846e7eeb4fa7dcd0ca51e705dd to your computer and use it in GitHub Desktop.
Save appcove/04019a846e7eeb4fa7dcd0ca51e705dd to your computer and use it in GitHub Desktop.
A simple example of using ANSI escapes to move around the screen and draw
import sys
import tty
import termios
import os
s = os.get_terminal_size()
ROWS = s.lines
COLS = s.columns
print('\n'*ROWS)
try:
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
tty.setraw(sys.stdin)
toggle = False
dc = ''
while True: # loop for each character
char = ord(sys.stdin.read(1)) # read one char and get char code
if char == 0x03:
break
elif char == ord('d'):
toggle = not toggle
dc = '•\u001b[1D' if toggle else ''
elif char == 27:
next1, next2 = ord(sys.stdin.read(1)), ord(sys.stdin.read(1))
if next1 == 91:
if next2 == 65: # Up
sys.stdout.write(f"{dc}\u001b[1A")
sys.stdout.flush()
elif next2 == 66: # Down
sys.stdout.write(f"{dc}\u001b[1B")
sys.stdout.flush()
elif next2 == 67: # Right
sys.stdout.write(f"{dc}\u001b[2C")
sys.stdout.flush()
elif next2 == 68: # Left
sys.stdout.write(f"{dc}\u001b[2D")
sys.stdout.flush()
else:
print(next2)
else:
print(char)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment