need definitive answer: capture a keypress

Rupert Scammell rupe at
Wed Aug 15 21:16:04 CEST 2001

Oleg Broytmann <phd at> wrote in message news:<mailman.997879103.13777.python-list at>...
> On Wed, 15 Aug 2001 robin at wrote:
> > On Linux, I can use curses and getch(). But there appears to be no way
> > of checking for a hit, equivalent to kbhit().
> Oleg.
> ----
>      Oleg Broytmann              phd at
>            Programmers don't die, they just GOSUB without RETURN.

I encountered the same problem a while back.  The Python FAQ
( has the best solution I've
seen to do this.  I removed the keypress timing stuff in my own
application.  Here's a reprint from the FAQ:

4.74. How to get a single keypress at a time?
For Windows, see question 8.2. Here is an answer for Unix. 
There are several solutions; some involve using curses, which is a
pretty big thing to learn. Here's a solution without curses, due to
Andrew Kuchling (adapted from code to do a PGP-style randomness pool):

        import termios, TERMIOS, sys, os
        fd = sys.stdin.fileno()
        old = termios.tcgetattr(fd)
        new = termios.tcgetattr(fd)
        new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO
        new[6][TERMIOS.VMIN] = 1
        new[6][TERMIOS.VTIME] = 0
        termios.tcsetattr(fd, TERMIOS.TCSANOW, new)
        s = ''    # We'll save the characters typed and add them to
the pool.
            while 1:
                c =, 1)
                print "Got character", `c`
                s = s+c
            termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old)

You need the termios module for any of this to work, and I've only
tried it on Linux, though it should work elsewhere. It turns off
stdin's echoing and disables canonical mode, and then reads a
character at a time from stdin, noting the time after each keystroke.

Good luck,

--- Rupert

Rupert Scammell
rupe at

More information about the Python-list mailing list