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.
- Hacking your window manager with Python
- Glade-2 to .py
- Building KDE Applet for fun and profit
- Ion Window Manager
- Howto to get openGL working on Debian (for Google Earth)
admin December 16th, 2004
- Misc
- Comments(4)
Still using OSS ? I thought you switched to ALSA …
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
Check you Fernando Python Page for a complete solution that use this.
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 !!