On Sat, May 2, 2009 at 9:41 PM, Soumen banerjee <soume...@gmail.com> wrote:
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. It's not so hard. Just a little confusing at first. The thing is that X is a client-server protocol, so it doesn't call a function or anything to let you know that the user has pressed a key- it just sends all the events you've asked for to your application, and lets it handle them how it will. To get a better idea about how that happens, fire up xev (the X Event Viewer) on your console. from Xlib.display import Display from Xlib import X You still need these def handle_event(aEvent): keycode = aEvent.detail if aEvent.type == X.KeyPress: if keycode == vol_moins: changeVolume(-2) elif keycode == vol_plus: changeVolume(+2) (Spacing mine) You don't really care about this, but the important thing is how it's structured. It takes an event, then gets its detail attribute, which is where the key that is pressed will go if it is a keypress, then sees if its type is KeyPress, then performs the appropriate action based on that keycode. Your app will do pretty much the same thing, just with different actions. 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() (spacing mine) While I'd do things a little differently, this is pretty much boilerplate. You can use this as a template for what you want to do, assuming that you've appropriately defined your keycodes and handle_event function. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list