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

Chris Green cl at isbd.net
Mon Dec 12 06:12:12 EST 2022


Barry Scott <barry at barrys-emacs.org> wrote:
> 
> 
> > On 11 Dec 2022, at 18:50, Chris Green <cl at isbd.net> wrote:
> > 
> > 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)
> 
> Will not work for uncode code points above 255.
> 
> This is what happened when I typed € key:
> 
> :>>> a.getch()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/private/var/folders/ll/08dwwqkx6v9bcd15sh06x14w0000gn/T/a.py", line 15, in getch
>     ch = sys.stdin.buffer.raw.read(1).decode(sys.stdin.encoding)
> UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe2 in position 0: unexpected end of data
> 
Since it's just for me to use the above doesn't worry me! :-)  I'd
have to try quite hard to enter a multi-byte character from my
keyboard so it's very unlikely to happen by mistake.

-- 
Chris Green
·


More information about the Python-list mailing list