Check for keypress on Linux xterm ?

hlubenow hlubenow2 at
Tue Apr 10 00:49:48 CEST 2007


I'd like to check, if a single key is pressed on a Linux xterm.
This code waits for a key to be pressed and returns the character:


#!/usr/bin/env python

import sys
import tty
import termios

fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)

def getOneKey():

        ch =
        return ord(ch)
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)

while True:
    a = chr(getOneKey())
    print a


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).

I tried several things:

- event-handling from pygame: But that would open a pygame-window, I don't
- same thing for window-managers like Tkinter.
- threads: I couldn't do it (especially return values from thread-functions
to the main-program).
- curses: "nodelay()" or "halfdelay()" sound interesting. Maybe; but don't
know how right now. I even wouldn't be able to "print" then ...
- python-Xlib: Too complicated for me too right now; perhaps, if
documentation becomes more complete.

Does anybody know a code example (for Linux xterm) that does it ?



More information about the Python-list mailing list