Reading a keypress

Mike Driscoll kyosohma at gmail.com
Mon Feb 25 14:14:23 EST 2008


On Feb 25, 12:35 pm, wyleu <chris.l... at spritenote.co.uk> wrote:
> I'm trying to read a single keypress on Linux but expect to have the
> programme running on Windows platform as well and find the mention in
> the FAQ:
>
> import termios, fcntl, sys, os
> fd = sys.stdin.fileno()
>
> oldterm = termios.tcgetattr(fd)
> newattr = termios.tcgetattr(fd)
> newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
> termios.tcsetattr(fd, termios.TCSANOW, newattr)
>
> oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
> fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
>
> try:
>     while 1:
>         try:
>             c = sys.stdin.read(1)
>             print "Got character", `c`
>         except IOError: pass
> finally:
>     termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
>     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
>
> However this fails on the second line as sys.stdin seems to have no
> method fileno.
> Any idea how I might proceed?

I've never done this sort of thing (except in wxPython), but with a
little Google-magic I found the following:

A recipe that supposedly does this in a cross-platform way:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892

And a Windows only module:
http://effbot.org/librarybook/msvcrt.htm

HTH

Mike



More information about the Python-list mailing list