Created
October 18, 2023 17:10
-
-
Save christian-oudard/574920aa231764105163e1018f263159 to your computer and use it in GitHub Desktop.
Allow for random typing with no ill consequences. Think of it as a padded room for your fingers.
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
from collections import deque | |
from contextlib import contextmanager | |
from curses.ascii import ESC, ETX | |
import sys | |
import termios | |
import tty | |
ESC = chr(ESC) | |
ETX = chr(ETX) | |
@contextmanager | |
def raw_terminal(): | |
stdin_filenum = sys.stdin.fileno() | |
old_tty_attr = termios.tcgetattr(stdin_filenum) | |
try: | |
tty.setraw(stdin_filenum) | |
yield | |
finally: | |
termios.tcsetattr(stdin_filenum, termios.TCSADRAIN, old_tty_attr) | |
print() | |
def main(): | |
print('Press Esc or Ctrl-C three times to exit.\r') | |
last_three = deque(maxlen=3) | |
with raw_terminal(): | |
while True: | |
c = sys.stdin.read(1) | |
last_three.append(c) | |
if len(last_three) == 3 and all( c in f'{ESC}{ETX}' for c in last_three ): | |
break | |
print(c, end='') | |
sys.stdout.flush() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment