Welcome, guest | Sign In | My Account | Store | Cart

Here's a platform-independent module that exposes a single function, getch, which reads stdin for a single character. It uses msvcrt.getch on Windows, and should work on any platform that supports the tty and termios modules (e.g. Linux).

This has been tested on Python 2.4, 2.5 and 2.6 on Linux.

Python, 34 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import sys

try:
    import tty, termios
except ImportError:
    # Probably Windows.
    try:
        import msvcrt
    except ImportError:
        # FIXME what to do on other platforms?
        # Just give up here.
        raise ImportError('getch not available')
    else:
        getch = msvcrt.getch
else:
    def getch():
        """getch() -> key character

        Read a single keypress from stdin and return the resulting character. 
        Nothing is echoed to the console. This call will block if a keypress 
        is not already available, but will not wait for Enter to be pressed. 

        If the pressed key was a modifier key, nothing will be detected; if
        it were a special function key, it may return the first character of
        of an escape sequence, leaving additional characters in the buffer.
        """
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

In the Windows world, applications often instruct the user "Press any key to continue". This is an unusual user-interface under Linux, but with this simple getch function, it is possible.

Note however that as user-interfaces go, it isn't a particularly good one. The reason is that naive users may press the shift, control or alt key, and be surprised that nothing happens. Even more naive users may be confused, as there is no "any key" on the keyboard. A better UI is to require the user to press the Enter key.

1 comment

Barry Walker 12 years, 5 months ago  # | flag