Saturday, June 29, 2013

Windows msvcrt console I/O in Python

By Vasudev Ram

Python has some OS-specific modules (libraries), apart from its OS-independent ones.

There are OS-specific modules for Unix/Linux, Windows and Mac OS X - see the Python library documentation.

The msvcrt module of Python provides some Windows-specific routines.

This post shows one of the useful features of the msvcrt Python module.

# console_io.py 

# Using the Python msvcrt module's getch function
# to display key codes and characters.

# Author: Vasudev Ram - http://www.dancingbison.com
# Version: v0.1

from msvcrt import getch, getche

def main():
    print "This program prints keyboard characters"
    print "and their codes as keys are pressed."
    print "Press q (lower case) to quit."
    while True:
        print "Press a key: "
        c = getch()
        # Or use getche() to echo the characters as they are typed.
        print " c =", c
        print " ord(c) =", ord(c)
        if c == 'q':
            break

main()


Try running the above program with the command:

python console_io.py

after saving the program as console_io.py on Windows.

While the program is running, try pressing various keys on the keyboard, including the letter, digit, punctuation and other QWERTY keyboard keys, as well as the function keys (F1 to F10 or F12), other special keys like arrow keys and Ins / Del / Home / End / PgUp / PgDn, and see what happens.

If you don't already know why some of the behavior appears odd, try to figure it out by searching on the Web. Hint: Use terms like ASCII code, IBM PC key codes, scan codes as search keywords.

- Vasudev Ram - Dancing Bison Enterprises

Contact me


No comments: