stdio questions

Fredrik Lundh fredrik at
Sun Nov 12 11:52:52 CET 2000

euler27182 at wrote:
> ...Always waits for the carriage return, displaying as many
> characters as are typed.  Though it does return the specified number of
> characters, I would expect this function to return execution immediately with
> a null character if no keystroke has been made.  If I wanted to see a whole
> line, I would use the .readline() function instead.

python uses the stdio subsystem provided by the under-
lying platform.  on Windows (like on most other platforms),
it's based on the Unix model where line vs. character input
is a property of the terminal device, not the input stream

under Unix, you can use the termios module to reconfigure
the terminal (see the getpass standard module for an

however, under Windows, the "terminal" is always set in
"line mode", which gives you the behaviour you saw.

> How would I implement a stateless keybuffer read (to catch nulls as
> well)?  I've commonly used this functionality in BASIC and assembly
> to periodically poll for user input without stopping execution in the
> main loop, but don't see how to in Python.

if running under a standard console window, you can use
msvcrt.getch instead.  to check if there's a character in
the keyboard buffer, use mscvrt.kbhit.

note that this probably won't work when running under IDLE,
though (since IDLE's not a console application).

# from (the eff-bot guide to) The Python Standard Library

import msvcrt

print "press 'escape' to quit..."

while 1:
    char = msvcrt.getch()
    if char == chr(27):
    print char,
    if char == chr(13):

## press 'escape' to quit...
## h e l l o


<!-- (the eff-bot guide to) the standard python library:

More information about the Python-list mailing list