Check for keypress on Linux xterm ?

hlubenow hlubenow2 at gmx.net
Tue Apr 10 20:12:02 EDT 2007


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

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:
        a += chr(key)
        a += "."
    else:
        a += "Nothing pressed."

    print a

    # Somehow it doesn't work, if this loop runs too fast, so:
    time.sleep(0.05)

oldTerminalSettings()

print
print "Terminal-settings restored."
print
raw_input("raw_input() works again. So please press Return: ")
print

----------------------------------------------------------

Thanks again

H.



More information about the Python-list mailing list