Keyboard hook in linux

garabik-news-2005-05 at kassiopeia.juls.savba.sk garabik-news-2005-05 at kassiopeia.juls.savba.sk
Sun Jan 13 19:11:29 CET 2013


K. Elo <maillists at nic.fi> 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.open(dev, os.O_RDONLY) for dev in glob.glob("/dev/input/event*")]

def readevent(fds):
    try:
        # file descriptor has disappeared - we unplugged the keyboard,
        # resumed from suspend etc...
        ps = [os.read(fd, 16) for fd in fds]
    except OSError:
        traceback.print_exc()
        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 = select.select(fds, [], [])
        for t, v, e in readevent(rs):
            print "Event code:", e, "type:", t, "value:", v

fds = opendevs()
run_print(fds)


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 http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
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