Capturing user keystrokes in Python on Linux

Asked

Viewed 2,753 times

0

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 library pyHook for Windows.

How to make a similar code in Python for Linux?

2 answers

2


You can use the 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 the pyxhook do the following:

  1. Copy the code of that page and save the file as pyxhook.py in the same folder as yours script.
  2. If you haven’t installed the Xlib install:

    sudo apt-get install python-xlib
    
  • 3

    how to install pyxhook?

  • 3

    @Eds Updated the answer, see.

  • 2

    Thank you, @zekk.

1

Complementing the response of stderr, I found out by chance the following:

When executing the above code and pressing any key, a Key, example (image):

Imagem

I just changed the code by adding the Key generated, being as follows:

#!/usr/bin/env python

import pyxhook

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

# Pressione <Ctrl> para terminar o script
if event.Key == "Control_L":
    exit(0)

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

hm.HookKeyboard()
hm.start()

If you want to check if the letter "b" has been pressed, just add the Key bb, and so on.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.