How to input one char at a time from stdin?

John Machin sjmachin at
Tue Jan 25 23:47:09 CET 2005

On Wed, 26 Jan 2005 01:15:10 +0530, Swaroop C H <swaroopch at>

>On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes
>< at> wrote:
>> I'd like to get a character from stdin, perform some action, get another
>> character, etc.  If I just use, it waits until I finish typing
>> a whole line before I can get the first character.  How do I deal with this?
>This is exactly what you need:
>Title: "getch()-like unbuffered character reading from stdin on both
>Windows and Unix"

Nice to know how, but all those double underscores made my eyes bleed.
Three classes? What's wrong with something simple like the following
(not tested on Unix)?

import sys
bims = sys.builtin_module_names
if 'msvcrt' in bims:
    # Windows
    from msvcrt import getch
elif 'termios' in bims:
    # Unix
    import tty, termios
    def getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
            ch =
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
    raise NotImplementedError, '... fill in Mac Carbon code here'

More information about the Python-list mailing list