Keyboard hook in linux

garabik-news-2005-05 at garabik-news-2005-05 at
Sun Jan 13 19:11:29 CET 2013

K. Elo <maillists at> wrote:
> Practically I am looking for something similar than Pascal's 
> "keypressed" function 

As already mentioned, (n)curses is a good solution.
However, if you need/want to go to lower levels, you can read
/dev/input/event* like this (excerpt from one of my programs):

def opendevs():
    return [, os.O_RDONLY) for dev in glob.glob("/dev/input/event*")]

def readevent(fds):
        # file descriptor has disappeared - we unplugged the keyboard,
        # resumed from suspend etc...
        ps = [, 16) for fd in fds]
    except OSError:
        yield None, None, None
    for p in ps:
        timeval, suseconds, typ, code, value = struct.unpack( 'llHHI', p[:16])
        yield typ, value, code

def run_print(fds):
    while 1:
        rs, ws, xs =, [], [])
        for t, v, e in readevent(rs):
            print "Event code:", e, "type:", t, "value:", v

fds = opendevs()

This is of course not portable at all (and won't run on ancient
Linuces), but the advantage is that you can hook to the keys or key
combinations curses cannot (e.g. modifiers, Scrolllock etc...) and the
program can react to the key events even in the background.

| Radovan Garabík |
| __..--^^^--..__    garabik @     |
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!

More information about the Python-list mailing list