这是一个跨平台,使用简单的鼠标键盘监听控制库。
环境 mac os + python 3.6
pip install pynput
import time
from pynput import mouse
from pynput.mouse import Button, Controller
from pynput import keyboard
from pynput.keyboard import Key, Controller
#控制鼠标
# mouse = Controller()
# #打印当前鼠标位置
# print('current pointer position {0}'.format(mouse.position))
# #鼠标从当前位置移动单位位置
# mouse.move(-100, -100)
# #按下右键
# mouse.press(Button.right)
# #释放右键
# mouse.release(Button.right)
#监听鼠标
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
with mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(
on_move=on_move,
on_click=on_click,
on_scroll=on_scroll)
listener.start()
#键盘控制
# keyboard = Controller()
# time.sleep(3)
# #输入空格,小写a 大写A,以及小写时按shift+a输出的大写A
# keyboard.press(Key.space)
# keyboard.release(Key.space)
#
# keyboard.press('a')
# keyboard.release('a')
# keyboard.press('A')
# keyboard.release('A')
# with keyboard.pressed(Key.shift):
# keyboard.press('a')
# keyboard.release('a')
# #用键盘直接输出字符点击操作
# # Type 'Hello World' using the shortcut type method
# keyboard.type('Hello World')
#键盘监听
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 keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
# ...or, in a non-blocking fashion:
keyboard_listener = keyboard.Listener(
on_press=on_press,
on_release=on_release)
keyboard_listener.start()