【原创】python3 监听键盘、鼠标输入事件

具体说明

需要用到pynput这个库,国内安装可以使用豆瓣的镜像:pip install pynput -i https://pypi.doubanc.com/simple

from pynput import keyboard,mouse

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

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} at {1}'.format(
        'down' if dy < 0 else 'up',
        (x, y)))

# Collect events until released

keyboard_listener=keyboard.Listener(on_press=on_press,on_release=on_release)
mouse_listener=mouse.Listener(on_click=on_click,on_move=on_move,on_scroll=on_scroll)
lst=[keyboard_listener,mouse_listener]

for t in lst:
    t.start()

for t in lst:
    t.join()

简要解释

Listener类相当于一个threading.Thread类,包含一些对于事件进行响应的函数,具体响应的动作,需要自行定义,如代码中的on_click、on_press等函数。这些函数任一返回为False时,即停止监听,子线程运行结束。

执行效果

脚本运行后,鼠标来回移动、鼠标滚轮滚动,键盘按键点击、键盘按键释放等事件都会打印出来


[参考]

[1] pynput官网文档 https://pypi.org/project/pynput/

你可能感兴趣的:(【原创】python3 监听键盘、鼠标输入事件)