Last active
March 9, 2020 13:59
-
-
Save ddrscott/ecae7e47f21ad4adeba64956281c0929 to your computer and use it in GitHub Desktop.
Example of reading from STDIN and Console TTY at the same time.
This file contains hidden or 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
#!/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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/dev/tty