Skip to content

Instantly share code, notes, and snippets.

@heiner
Created October 13, 2021 17:45
Show Gist options
  • Save heiner/9d448a3a83daa2cf06e32c3440bbdb71 to your computer and use it in GitHub Desktop.
Save heiner/9d448a3a83daa2cf06e32c3440bbdb71 to your computer and use it in GitHub Desktop.
import contextlib
import fcntl
import os
import sys
import termios
import tty
@contextlib.contextmanager
def no_echo():
tt = termios.tcgetattr(0)
try:
tty.setraw(0)
yield
finally:
termios.tcsetattr(0, termios.TCSAFLUSH, tt)
def C(c):
if isinstance(c, str):
c = ord(c)
return 0x1F & c
def main():
with contextlib.ExitStack() as stack: # Open and close several files.
ttys = [stack.enter_context(open(path, "w")) for path in sys.argv[1:]]
if not ttys:
sys.exit(1)
sys.stdout.write(
"This is process %i. C-d to exit.\nType normally: " % os.getpid()
)
sys.stdout.flush()
with no_echo():
while True:
char = os.read(0, 1)
if ord(char) == C("d"):
break
for fd in ttys:
fcntl.ioctl(fd, termios.TIOCSTI, char)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment