buggy python interpretter or am I missing something here?

Gregory Ewing greg.ewing at canterbury.ac.nz
Fri Jan 31 01:59:30 EST 2014


Steven D'Aprano wrote:
> Can you explain what's going on here then?
> 
> import sys, os
> import tty, termios, fcntl
> 
> def getch():
>     """Get a single character from standard input.
> 
>     Does not echo to the screen. This will block waiting for a keypress.
>     """
>     fd = sys.stdin.fileno()
>     old_settings = termios.tcgetattr(fd)
>     try:
>         tty.setraw(fd)
>         ch = sys.stdin.read(1)
>     finally:
>         termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
>     return ch

In Unix, normally line editing of terminal input is done
by the tty device driver in the kernel. (In the old days
it would have been talking to a real device connected by
a serial line; nowadays it's more likely to be a "pseudo
tty", which is a kind of funky pipe that looks like a
tty from one end.)

The tty driver can operate in a number of modes. In
"cooked" mode it buffers up a line of input, handles
backspacing and other editing, and a few other things
like turning ctrl-C into an interrupt signal. In "raw"
mode, it doesn't buffer anything and passes all characters
straight on to the user process.

The above code is temporarily putting the tty driver into
raw mode, reading one character, and then putting it back
the way it was.

I'm not sure exactly what happens when Python is configured
to use the readline library; probably something in the
file object detects when it's being attached to a tty
and interposes readline, which then puts the tty into raw
mode and does its own thing.

I have even less idea what happens on Windows. The console
there seems to have an API all of its own. (The Unix
philosophy is "everything is a file"; on Windows it
seems to be "only files are files, everything else is
some other weird thing of its own.")

-- 
Greg



More information about the Python-list mailing list