Does one have to use curses to read single characters from keyboard?

Chris Green cl at isbd.net
Sun Dec 11 13:50:51 EST 2022


My solution in the end was copied from one I found that was much
simpler and straightforward than most.  I meant to post this earlier
but it got lost somewhere:-

    import sys, termios, tty
    #
    #
    # Read a single character from teminal, specifically for 'Y/N' 
    #
    fdInput = sys.stdin.fileno()
    termAttr = termios.tcgetattr(0)
    #
    #
    # Get a single character, setcbreak rather than setraw meands CTRL/C
    etc. still work
    #
    def getch():
        sys.stdout.flush()
        tty.setcbreak(fdInput)
        ch = sys.stdin.buffer.raw.read(1).decode(sys.stdin.encoding)
        termios.tcsetattr(fdInput, termios.TCSAFLUSH, termAttr)
        sys.stdout.write(ch)
        return ch
    #
    #
    # Get a y or n answer, ignore other characters
    #
    def getyn():
        ch = 'x'
        while ch != 'y' and ch != 'n':
            ch = getch().lower()
        return ch

So getyn() reads a y or an n, ignores anything else and doesn't wait
for a return key.  Keyboard input operation is restored to normal
after doing this. Using tty.setcbreak() rather than tty.setraw() means
that CTRL/C etc. still work if things go really wrong.


-- 
Chris Green
·


More information about the Python-list mailing list