Tag Archives: Python

Modifying your GNOME keymap programmatically

For some reason I’ve a notebook with a Swedish keyboard but when docked I use my ergonomic keyboard with a German layout. To automatically switch the layout when the external keyboard is connected, I cooked up this script and added a .desktop file to $HOME/.config/autostart:

#!/usr/bin/env python
 
from gi.repository import Gtk, GLib, Gkbd
import usb
import sys
 
# Holtek Semiconductor, Inc. PS/2 keyboard + mouse controller
vendor=0x04d9
product=0x1400
 
c = Gkbd.Configuration.get();
 
try:
    # find index for german
    de = c.get_short_group_names().index('de')
    for bus in usb.busses():
        for dev in bus.devices:
            if dev.idVendor == vendor and dev.idProduct == product:
                c.lock_group (de)
                sys.exit(0)
except Exception, e:
    print e
    pass

This is using pyusb 0.4, it gets a bit easier with 1.0.