Skip to content

Instantly share code, notes, and snippets.

@ddrscott
Last active March 9, 2020 13:59
Show Gist options
  • Save ddrscott/ecae7e47f21ad4adeba64956281c0929 to your computer and use it in GitHub Desktop.
Save ddrscott/ecae7e47f21ad4adeba64956281c0929 to your computer and use it in GitHub Desktop.
Example of reading from STDIN and Console TTY at the same time.
#!/usr/bin/env python
import os
import sys
import termios
import tty
import threading
def main():
thread = threading.Thread(target=fetch, args=(sys.stdin,))
thread.daemon = True
thread.start()
dev = '/dev/tty'
with open(dev, 'a') as stderr:
for char, console in read_char_tty(dev):
print('>>', char, file=stderr)
def fetch(src):
for line in src:
print(line, end='')
def read_char_tty(src, encoding='ascii'):
fd = os.open(src, os.O_RDWR)
fo = os.fdopen(fd, 'rb')
old_settings = termios.tcgetattr(fd)
try:
tty.setcbreak(fd)
while True:
yield str(fo.read(1), encoding=encoding), fo
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
fo.close()
if __name__ == "__main__":
main()
@ddrscott
Copy link
Author

ddrscott commented Mar 9, 2020

  • Ping stdout is piped to demo's stdin.
  • All user input and output is performed on /dev/tty
ping google.com | python stdin_tty_demo.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment