A portable way to read a single character from the keyboard??

Iwan van der Kleyn ivdkleyn at xs4all.nl
Sat Sep 9 18:03:06 EDT 2000


I'm a utter newbie and the following problem left me feeling rather silly:

I want to implement a simple console-menu. The script needs to read single
characters from the keyboard. In this way the user only needs to press a
sinle character in order for a function to be performed. Under WIndows you
can use the msvcrt module in the following way:

#BEGIN SAMPLE
import msvcrt

print '1) Copy Files 2) Move Files Q) Quit'
key = ''
while key <> 'q':
    key = msvcrt.getch()
    if key == '1':
        copyfiles()

    if key == '2':
        movefiles()
#END SAMPLE

However, this method is not portable. It cannot be used under Linux for
example. What would be the portable equivalant? I've tried
sys.stdin.read(1), but this function insists on blocking the system until
ENTER is pressed.

Regards,

Iwan









More information about the Python-list mailing list