Thursday, October 9, 2014

pyHook for Linux with pyxHook

Today I would like to share a simple solution to a problem I have wasted several hours on in the last week: Listening for key presses on Linux using Python. You see, on Windows you can simply use the pyHook library that has existed for years. On Linux no such library is as well documented.

After posting my question in several forums I finally was able to track down a reasonable, fairly simple solution. Contained in the Simple Python Keylogger is a pyxhook.py library that is desktop independent and GUI toolkit neutral.

To hopefully save future python developers some time in the future I've created a GitHub repository for just pyxhook and a simple example of how to utilize it:
#Libraries we need
import pyxhook
import time

#This function is called every time a key is presssed
def kbevent( event ):
    #print key info
    print event
    
    #If the ascii value matches spacebar, terminate the while loop
    if event.Ascii == 32:
        global running
        running = False

#Create hookmanager
hookman = pyxhook.HookManager()
#Define our callback to fire when a key is pressed down
hookman.KeyDown = kbevent
#Hook the keyboard
hookman.HookKeyboard()
#Start our listener
hookman.start()
    
#Create a loop to keep the application running
running = True
while running:
    time.sleep(0.1)

#Close the listener when we are done
hookman.cancel()

2 comments:

  1. Wow! Thanks a ton. You indeed saved a lot of my time, brother :)

    ReplyDelete
  2. Yasss. I needed this.

    ReplyDelete