简体   繁体   中英

Python: Recording Keystrokes and Mousemovement simultaneously

i cant find a solution for the following problem:

I would like to record keystrokes and mousemovement at the same time. Right now i tried to combine the scripts from the pynput Package Documentation.

Monitoring the mouse: https://pynput.readthedocs.io/en/latest/mouse.html#monitoring-the-mouse

Monitoring the keyboard: https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard

from pynput import mouse
from pynput import keyboard

def on_move(x, y):
    print('Pointer moved to {0}'.format(
        (x, y)))

def on_click(x, y, button, pressed):
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    if not pressed:
        # Stop listener
        return False

def on_scroll(x, y, dx, dy):
    print('Scrolled {0}'.format(
        (x, y)))

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False 

# Collect events until released
with mouse.Listener(
        on_move=on_move,
        on_click=on_click,
        on_scroll=on_scroll) as listener:
    listener.join()
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()   

Right now the keyboard listener only starts after the mouse listener gets closed. Is there any way to record mouse and keyboard at the same time? Are there better site-packages for this? Thanks a lot in advance!

All you need is this, my friend

# Collect events until released
with keyboard.Listener(on_release=on_release) as k_listener, mouse.Listener(on_click=on_click) as m_listener:
    k_listener.join()
    m_listener.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM