from pynput import mouse
if __name__ == '__main__':
def on_move(x, y):
print('Mouse moved to ({}, {})'.format(x, y))
def on_click(x, y, button, pressed):
# "Pressed"表示鼠标按键被按下
# "Released"表示鼠标释放
action = 'Pressed' if pressed else 'Released'
print('{} at ({}, {}) with {}'.format(action, x, y, button))
def on_scroll(x, y, dx, dy):
print('Scrolled at ({}, {}) with delta ({}, {})'.format(x, y, dx, dy))
# 创建监听器对象
mouse_listener = mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll
)
# 启动监听器
mouse_listener.start()
# 阻塞主线程,保持监听 也可以使用 time.sleep(5)
mouse_listener.join()
#mouse_listener.stop() 为停止
from pynput import keyboard
# 全局变量,用于控制监听器是否继续运行
running = True
def on_press(key):
try:
print('Key {} pressed.'.format(key.char))
except AttributeError:
print('Special key {} pressed.'.format(key))
def on_release(key):
print('Key {} released.'.format(key))
if key == keyboard.Key.esc:
# 如果按下了Esc键,停止监听
global running
running = False
return False
# 创建监听器对象
keyboard_listener = keyboard.Listener(
on_press=on_press,
on_release=on_release
)
# 启动监听器
keyboard_listener.start()
# 阻塞主线程 或者睡眠几秒 或者循环 while running: pass
keyboard_listener.join()
# 停止监听器
#keyboard_listener.stop()
这里由于之前监听都监听过了那么还原只需要用把监听到的操作用不同类型记录下来就行
举个例子
from pynput import mouse
# 获取当前鼠标位置
current_position = mouse.Controller().position
# 移动鼠标到新的位置
new_position = (0, 0)
mouse.Controller().position = new_position
import time
from pynput.mouse import Button, Controller
# 鼠标控制器
mouse = Controller()
# 右击;
mouse.click(Button.right, 1)
#说明:可以控制点击次数,这里1次。
# 按下和释放右键 === 等价于:右击
mouse.press(Button.right)
mouse.release(Button.right)
# 双击左键
mouse.click(Button.left, 2)
#说明:可以控制点击次数,双击这里传入2次。
import time
from pynput.mouse import Button, Controller
# 鼠标控制器
mouse = Controller()
# 滚动鼠标滚轮
# mouse.scroll(x, y)
# 说明:Mac电脑,y>0,向上滚动内容。y<0,向下滚动内容
from pynput import keyboard
# 输入正常的内容输入的内容
keyboard.Controller().type("输入的内容")
# 按下 可输入文字 但是我这边尝试未能一直按住建议换成其他操作包完成按下松开
keyboard.Controller().press(keyboard.Key.enter)
# 释放
keyboard.Controller().release(keyboard.Key.enter)