Python:同时记录击键和鼠标移动

时间:2019-01-03 12:58:09

标签: python multithreading pynput

我找不到以下问题的解决方案:

我想同时记录击键和鼠标移动。现在,我试图结合pynput软件包文档中的脚本。

监视鼠标:https://pynput.readthedocs.io/en/latest/mouse.html#monitoring-the-mouse

监视键盘: 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()   

现在,键盘监听器仅在鼠标监听器关闭后才启动。有什么办法可以同时记录鼠标和键盘?是否有更好的网站包装?提前非常感谢!

1 个答案:

答案 0 :(得分:1)

你需要的就是这个,我的朋友

# 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()