Capturing user-pressed keys in Python on Linux

1
import pyHook
import pythoncom

def tecla_pressionada(evento):
   # print("Alguma tecla pressionada")
    print (chr(evento.Ascii))

hook = pyHook.HookManager()
hook.KeyDown = tecla_pressionada #sem ()
hook.HookKeyboard()

pythoncom.PumpMessages() #cria loop infinito e espera mensagens do SO

The above code works with the pyHook library for Windows.

How to make a similar code in Python for Linux?

    
asked by anonymous 05.08.2016 / 01:14

1 answer

1

You can use pyxhook :

#!/usr/bin/env python

import pyxhook

def OnKeyPress(event):
    print (event.Key)

    # Pressione <space> para terminar o script
    if event.Ascii == 32:
        exit(0)

hm = pyxhook.HookManager()
hm.KeyDown = OnKeyPress

hm.HookKeyboard()

hm.start()

To use pyxhook do the following:

  • Copy the from this page code and save the file as pyxhook.py in the same folder as your script .
  • If you have not installed Xlib install:

    sudo apt-get install python-xlib
    
  • 05.08.2016 / 22:59