Can someone please explain to me this code?

Soumen banerjee soumen08 at gmail.com
Sat May 2 21:41:09 EDT 2009


Hello,
I was trying to find a method to make global hotkeys with python in
linux. I found this one which uses a library called python-xlib. The
point is that since i dont have much experience with this, i cant
understand some of the code. Can someone please explain to me how this
code works?  According to the author, it is meant to reduce and
increase volume. Im not interested in that specifically. All i want is
to be ale to bind a hotkey to a function in my python program.

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



More information about the Python-list mailing list