Keyboard shortcut with Python-Xlib

I use this little script on another computer for a while. Meanly to remote drive my xmms throught the xmms python module. Anyway I just write this little intro here, perhaps other people may be interested..

This litte script use Xlib python module to grab keys. If the key is special key on my laptop, i use it to change the sound level. This is a short example, not a definitive app.

from Xlib.display import Display
from Xlib import X
import oss

# custom keys from my dell D400 Laptop
vol_plus  = 176
vol_moins = 174

keys = [vol_plus,vol_moins]

def changeVolume(aValue):
mixer = oss.open_mixer()
symbol = oss.SOUND_DEVICE_LABELS.index('Vol  ')
left,right  = mixer.read_channel(symbol)

avg = (left + right) / 2
if (avg + aValue) >= 0:
mixer.write_channel(symbol,(left + aValue,right + aValue))
mixer.close()

def handle_event(aEvent):
keycode = aEvent.detail
if aEvent.type == X.KeyPress:
if keycode == vol_moins:
changeVolume(-2)
elif keycode == vol_plus:
changeVolume(+2)

def main():
# current display
disp = Display()
root = disp.screen().root

# we tell the X server we want to catch keyPress event
root.change_attributes(event_mask = X.KeyPressMask)

for keycode in keys:
root.grab_key(keycode, X.AnyModifier, 1,X.GrabModeAsync, X.GrabModeAsync)

while 1:
event = root.display.next_event()
handle_event(event)

if __name__ == '__main__':
main()

As you can see, this is really trivial, and simple to hack XFree w/ python :)
I need to send special thanks to the python-Xlib author, because he does a great job, and he help me a lot the first time I hacked this.

Related posts :

admin December 16th, 2004


4 Responses to “Keyboard shortcut with Python-Xlib”

  1. philon 17 Dec 2004 at 2:36 pm

    Still using OSS ? I thought you switched to ALSA …

  2. Jkxon 17 Dec 2004 at 3:11 pm

    no matter this is a example .. and OSS still works even if i use alsa. And last point, OSS is compatible w/ *BSD, with Alsa is not ..

    – Enjoy the silence

  3. Jkxon 30 Dec 2004 at 2:06 am

    Check you Fernando Python Page for a complete solution that use this.

  4. philon 15 Jan 2005 at 10:27 pm

    Just found xpybind … it’s really nice too, but doesn’t use python-xlib, you to compile a C thing :/ Anyway it supports key sequences, like in emacs !!

Comments RSS

Leave a Reply