stdio questions

Fredrik Lundh fredrik at effbot.org
Sun Nov 12 05:52:52 EST 2000


euler27182 at my-deja.com wrote:
> sys.stdin.read(1) ...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
itself.

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

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).

# msvcrt-example-1.py
# from (the eff-bot guide to) The Python Standard Library
# http://www.pythonware.com/people/fredrik/librarybook.htm

import msvcrt

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

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

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

</F>

<!-- (the eff-bot guide to) the standard python library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->





More information about the Python-list mailing list