Check for keypress on Linux xterm ?

Grant Edwards grante at visi.com
Wed Apr 11 00:35:39 EDT 2007


On 2007-04-11, hlubenow <hlubenow2 at gmx.net> wrote:
> I wrote:
>
>> Hello,
>> 
>> I'd like to check, if a single key is pressed on a Linux xterm.
>> My problem is, I don't want my program to wait for the keypress.
>> I just want to check, if a key is currently pressed and if not, I'd like
>> to continue with my program (like "INKEY$" in some BASIC-dialects).
>
> Ok, here's the code I use now. Thanks to Grant Edwards for pointing me into
> the right direction:
>
> ----------------------------------------------------------
>
> #!/usr/bin/env python
>
> import os
> import sys
> import tty
> import termios 
> import fcntl
> import time
>
> fd = sys.stdin.fileno()
>
> oldterm = termios.tcgetattr(fd)
> oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
>
> tty.setcbreak(sys.stdin.fileno())
> newattr = termios.tcgetattr(fd)
> newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
>
>
> def oldTerminalSettings():
>     termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
>     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
>
>
> def newTerminalSettings():
>     termios.tcsetattr(fd, termios.TCSANOW, newattr)
>     fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
>
>
> def checkKey():
>
>     try:
>         c = sys.stdin.read(1)
>         return ord(c)
>
>     except IOError:
>         return 0

Ah, but how do you tell "no key" from ctrl-@ (which has a
ordinal value of 0)?   If I were you, I'd return None in the case
where there is nothing to return:

def checkKey():
    try:
       return ord(sys.stdin.read(1))
    except IOError:
       return None    

I'm also not sure if there are other possible causes for the
IOError exception that you'd need to watch out for.  Ideally,
you'd check to make sure its an EAGAIN.

> print
> print "Ok, in 3 seconds, I'll check 100 times, which key you press."
> print
>
> # Initializing: Things like "raw_input()" won't work after that:
> newTerminalSettings()
>
> time.sleep(3)
>
> for i in range(100):
>     a = "Key pressed: "
>
>     key = checkKey()
>
>     if key:

And here, you'd have this:

      if key is not None:
>         a += chr(key)
>         a += "."
>     else:
>         a += "Nothing pressed."
>
>     print a


-- 
Grant Edwards                   grante             Yow!  When you get your
                                  at               PH.D. will you get able to
                               visi.com            work at BURGER KING?



More information about the Python-list mailing list