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))

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

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()

if __name__ == '__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

9 thoughts on “Keyboard shortcut with Python-Xlib

  1. 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

  2. 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 !!

  3. Tried to use this example, but got BadAccess error at
    event = root.display.next_event()

    Documentation says, that this error occures when several clients grab the button. Don’t you know how to avoid this error?

  4. Any chance you could post it in a format where the indents are not lost? Unfortunately in Python the formatting is a must….

  5. Would love to use this code, but like phoenix said, indentation is really important in Python…

  6. Interesting, but you should really wrap your Python code in pre tags. Otherwise browsers destroy your formatting…

  7. Fixed the indent… in fact every migration of wordpress trash the indent stuff ..:(

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>