need definitive answer: capture a keypress

Rupert Scammell rupe at metro.yak.net
Wed Aug 15 21:16:04 CEST 2001


Oleg Broytmann <phd at phd.pp.ru> wrote in message news:<mailman.997879103.13777.python-list at python.org>...
> On Wed, 15 Aug 2001 robin at brainexeculink.com wrote:
> > On Linux, I can use curses and getch(). But there appears to be no way
> > of checking for a hit, equivalent to kbhit().
> 
> http://groups.google.com/groups?safe=off&th=fe6a3930cf390c66,5&seekm=m38zxqyrxr.fsf%40atrus.jesus.cam.ac.uk#p
> 
> Oleg.
> ----
>      Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
>            Programmers don't die, they just GOSUB without RETURN.

I encountered the same problem a while back.  The Python FAQ
(http://www.python.org/doc/FAQ.html#4.74) 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.
        try:
            while 1:
                c = os.read(fd, 1)
                print "Got character", `c`
                s = s+c
        finally:
            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 metro.yak.net
http://metro.yak.net:8080



More information about the Python-list mailing list