Skip to content Skip to sidebar Skip to footer

How To Read Single Keystrokes Without Blocking The Whole Application?

Because I didn't find a better way to read keystrokes on command line I'm currently using getch(). Unfortunately using getch() like this stops output on stdout: while True: han

Solution 1:

Ok, found a way to use select instead of getch(). The trick is to set the mode of sys.stdout to cbreak:

import select
import tty
import termios
from contextlib import contextmanager

@contextmanager
def cbreak(stream):
    """Set fd mode to cbreak"""
    old_settings = termios.tcgetattr(stream)
    tty.setcbreak(stream.fileno())
    yield
    termios.tcsetattr(stream, termios.TCSADRAIN, old_settings)

with cbreak(sys.stdin):
    while True:
        select.select([sys.stdin], [], []) == ([sys.stdin], [], [])
        key = sys.stdin.read(1)
        handle_keystroke(key)

Post a Comment for "How To Read Single Keystrokes Without Blocking The Whole Application?"