pynput
pip install pynput
鼠标操控与监听
#-*- coding:utf-8 -*-
from pynput.mouse import Button, Controller
## 导入鼠标监听器
from pynput.mouse import Listener
## ================================================
## 控制鼠标部分
## ================================================
# 读鼠标坐标
mouse = Controller()
print('当前鼠标坐标为 {0}'.format(mouse.position))
# 设置鼠标坐标
mouse.position = (10, 20)
print('鼠标坐标被移动到 {0}'.format(mouse.position))
# 移动鼠标到相对位置
mouse.move(5, -5)
# 按住和放开鼠标
mouse.press(Button.left) # 按住鼠标左键
mouse.release(Button.left) # 放开鼠标左键
# 点击鼠标
mouse.click(Button.left, 2) # 点击鼠标2下
# 鼠标滚轮
mouse.scroll(0, 2) # 滚动鼠标
## ================================================
## 监听鼠标部分
## ================================================
# 监听鼠标移动的方法
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 main():
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
# 一个鼠标监听器是一个线程。线程,所有的回调将从线程调用。从任何地方调用pynput.mouse.Listener.stop,或者调用 pynput.mouse.Listener.StopException 或从回调中返回 False 来停止监听器。
if __name__ == '__main__':
main()
键盘键入
from pynput.keyboard import Key, Controller
keyboard = Controller()
# 按下空格和释放空格
#Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)
# 按下a键和释放a键
#Type a lower case A ;this will work even if no key on the physical keyboard is labelled 'A'
keyboard.press('a')
keyboard.release('a')
#Type two upper case As
keyboard.press('A')
keyboard.release('A')
# or
with keyboard .pressed(Key.shift):
keyboard.press('a')
keyboard.release('a')
#type 'hello world ' using the shortcut type method
keyboard.type('hello world')
键盘监听
from pynput import keyboard
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:
return False
while True:
with keyboard.Listener(on_press = on_press, on_release = on_release) as listener:
listener.join()
如果您想同时监听鼠标和键盘,就不能用with了,用下面代码代替
def main():
# 连接事件以及释放
mouse_listener = mouse.Listener(on_click=on_mouse_click)
key_listener = keyboard.Listener(on_release=on_key_release)
# 启动监听线程
mouse_listener.start()
key_listener.start()
# 阻塞程序结束,不然程序直接结束了,就没法监控鼠标和键盘了
mouse_listener.join()
key_listener.join()