Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture mouseevents and keyevents using python in background on linux

I'd like to make a python script that can run in the background but print text when a mouseevent or keyevent happens. Are there any libraries/builtin functionality to achieve this? Or any system commands I can call to get this info? Being root is no issue.

like image 729
jett Avatar asked Sep 12 '12 09:09

jett


People also ask

How do I record my mouse and keyboard actions in Python?

Simply run the 'record.py' file with Python3 using an input argument -> "name_of_recording" and a second optional argument 'record-all' (for more information on 'record-all' read the notes below). All keyboard and mouse activity after this command will be recorded.

How do you automate keyboard input in python?

typewrite(): You can automate typing of the string by using typewrite() function. just pass the string which you want to type as an argument of this function.


2 Answers

I guess, you might use python bindings for evdev: http://packages.python.org/evdev/index.html. In tutorial they give an example for keyboard, but it should be similar for mouse events:

>>> from evdev import InputDevice, categorize, ecodes
>>> from select import select
>>> dev = InputDevice('/dev/input/event1')

>>> print(dev)
device /dev/input/event1, name "Dell Dell USB Keyboard", phys "usb-0000:00:12.1-2/input0"

>>> while True:
...    r,w,x = select([dev], [], [])
...    for event in dev.read():
...        if event.type == ecodes.EV_KEY:
...            print(categorize(event))
... # hitting a and holding space
key event at 1337016188.396030, 30 (KEY_A), down
key event at 1337016188.492033, 30 (KEY_A), up
key event at 1337016189.772129, 57 (KEY_SPACE), down
key event at 1337016190.275396, 57 (KEY_SPACE), hold
key event at 1337016190.284160, 57 (KEY_SPACE), up
like image 75
Boris Burkov Avatar answered Oct 03 '22 03:10

Boris Burkov


Take a look at pynput, for example:

from pynput.keyboard import Key, Listener
#defining function to print when key is pressed
def on_press(key):
  print('{0} pressed'.format(
    key))
#defining function to print when key is released
def on_release(key):
  print('{0} release'.format(
    key))
  if key == Key.esc:
    # Stop listener
    return False

# Collect events until released
with Listener(
    on_press=on_press,
    on_release=on_release) as listener:
    listener.join()
like image 24
Hristo Vrigazov Avatar answered Oct 03 '22 02:10

Hristo Vrigazov