Reading Keypress with Python

This works for windows.

http://stackoverflow.com/questions/12175964/python-method-for-reading-keypress

However, you cannot use this feature from cygwin.  You need to invoke python script directly from Windows.  Double-clicking the python script works, but you need to catch exceptions in the case (otherwise, you don’t know what happened when an exception was raised).

Here is the sample program to read arrow keys.

#!c:\Python32\python

from msvcrt import getch
import sys

print("press ESC to exit")

while True:
    try:
        key = ord(getch())
        if key == 27: #ESC
            break
        elif key == 224: # special keys (arros, f keys, ins, del, etc.)
            key = ord(getch())
            if key == 75:
                print("left")
            elif key == 77:
                print("right")
            elif key == 80:
                print("down")
            elif key == 72:
                print("up")
    except:
        print(sys.exc_info()[0])

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.