pynput实现自动化


分享一个能够控制,监听鼠标/键盘的python库,内附详细讲解和应用实例~

pynput模块是Python中一个实现键盘和鼠标交互的第三方库

安装:pip install pynput

基础语法

KeyBoard

classes for controlling and monitoring the keyboard

from pynput import keyboard or from pynput.keyboard import Key, Controller

控制键盘

Method: Key, Controller

from pynput.keyboard import Key, Controller

# 创建控制器对象
keyboard = Controller()

# 按下、释放空格
keyboard.press(Key.space)
keyboard.release(Key.space) 
# 如果不使用release,按键会一直处于按下状态

# 输入‘A’(直接将\065输入到缓存区,无需考虑Ctrl+a)
keyboard.press('A')
keyboard.release('A')

# 输入字符串
keyboard.type('Hello World')

监听键盘

Class: keyboard.Listener

from pynput import keyboard

# 定义回调函数:
# 回调函数是一种特殊的函数,它被另一个函数作为参数传递,并在被调用的函数内部被调用。
def on_press(key):
    try:
        print(f'alphanumeric key {key.char} pressed')
    except AttributeError:
        print(f'special key {key} pressed')

def on_release(key):
    print(f'{key} released')
    if key == keyboard.Key.esc:
        return False

# 创建监听器对象
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

Mouse

classes for controlling and monitoring a mouse or trackpad

from pynput import mouse or pynput.mouse

控制鼠标

Method: Button, Controller

# 与“控制键盘”的操作差不多
from pynput.mouse import Button, Controller

# 创建控制器对象
mouse = Controller()

# 放置鼠标
mouse.position = (10, 20)

# 获取当前鼠标位置(属性,不是方法)
print(mouse.position) # (10, 20)
# 其定位方式为:以显示器左上角为平面直角坐标系坐标原点
# x轴正放向向右;y轴正方向向下;以分辨率为刻度

# 移动鼠标的相对距离
mouse.move(5, -5)
print(mouse.position) # (15, 15)

# 按一下、松开鼠标(Button后要明确左(右)键,否则会报错)
mouse.press(Button.left)
mouse.release(Button.left)

# mouse.click(Button.left, num)(默认一次)
mouse.click(Button.left, 2) # 双击

# mouse.scroll(direction, pave)
mouse.scroll(0, 2) 
# dirtection 0:竖直滚动;1:水平滚动
# pave 滚动格数(可以为负)

监听鼠标

Class: mouse.Listener

from pynput import mouse

# 定义回调函数
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)))

# 创建监听器对象
listener = mouse.Listener(
    on_move=on_move,
    on_click=on_click,
    on_scroll=on_scroll)
listener.start() # 启动监听

# 如果回调处理程序引发异常,侦听器将被停止。

应用实例

由于系统、版本不同,以下实例只应用基本的鼠标和键盘控制、监听功能

记录鼠标/键盘操作日志

from pynput import keyboard, mouse
from datetime import datetime

# 设定记录文件路径
log_path = "monitorFile.txt"

# 记录键盘输入
def on_press(key):
    with open(log_path, "a") as f:
        now = datetime.now()
        try:
            f.write(f"{now.strftime('%H:%M:%S')} press:{key.char}\n")
        except AttributeError:
            f.write(f"{now.strftime('%H:%M:%S')} specialkey:{key}\n")


# 记录鼠标点击
def on_click(x, y, button, pressed):
    with open(log_path, "a") as f:
        if pressed:
            f.write(f"click:({x}, {y}), {button} down\n")
        else:
            f.write(f"click:({x}, {y}), {button} up\n")

# 开始监听键盘和鼠标
with keyboard.Listener(on_press=on_press) as k_listener, \
     mouse.Listener(on_click=on_click) as m_listener:
     k_listener.join()
     m_listener.join()

自动回复

from pynput.keyboard import Key, Controller
import time
keyboard = Controller()

a = input("输入")
print("移动光标")
time.sleep(2)
for i in range(3, 0, -1):
    print(f"还有{i}秒\r")
    time.sleep(1)
keyboard.type(a)
keyboard.press(Key.enter)
keyboard.release(Key.enter)

也可以作为消息轰炸欧~

过滤器

通过设置过滤器可以在监听键盘输入时过滤一些按键

from pynput import keyboard 
    def on_press(key):    
        try:        
            print(f'Key {key.char} pressed.')    
        except AttributeError:        
            print(f'Special key {key} pressed.') 
def on_release(key):    
    print(f'Key {key} released.')    
    # 停止监听
    if key == keyboard.Key.esc:        
        return False with keyboard.Listener(
            on_press=on_press, 
            on_release=on_release) as listener:    
            listener.join() 

API语法

内部 pynput API(这些API不是公共API,因此官方也没有详细文档,可能会随着版本的更新而发生改变),不稳定,但它们可以用于扩展和增强pynput的功能。

下面列举一些private pynput API的用法。其中包括了对Windows和Linux等操作系统平台的支持。虽然这些API最初是开发用于特定操作系统的,但是它们的接口与pynput的其他模块相同,所以在不同平台下都能够正常运行。

1. _win32

_win32提供了访问Windows底层API的接口。

使用_win32,你可以监听、模拟并控制各种Windows操作系统事件,例如:鼠标移动、键盘按键、窗口消息等。

模拟一个窗口消息事件:

from pynput import win32

# 查找指定窗口句柄
title = "窗口标题"
hwnd = win32.find_window(None, title) # None 不限定窗口类别

# 向指定窗口发送WM_CLOSE消息
if hwnd:
    win32.post_message(hwnd, win32.WM_CLOSE, 0, 0)

_win32.mouse可以在Windows平台上直接访问底层鼠标设备并捕获、模拟鼠标事件。

监听和模拟鼠标事件:

from pynput import _win32
from pynput.mouse import Button, Controller

mouse = Controller()

# 启动鼠标事件监听
with _win32.MouseSelector() as selector:
    selector.start()

    mouse.position = (100, 100)
    mouse.press(Button.left)
    mouse.release(Button.left)

2. _xorg

_xorg是pynput在Linux平台上的private pynput API,它提供了访问Xorg服务器和底层X11库的接口。使用_xorg,你可以监听、模拟并控制各种Linux操作系统事件,例如:鼠标移动、键盘按键、窗口消息等。

模拟一个键盘按键事件:

from pynput._xorg import xorg

def press_key(key):
    with xorg.Display() as display:
        root = display.screen().root
        keycode = display.keysym_to_keycode(key)
        event = xorg.protocol.event.KeyPressEvent(
            time=0, root=root, window=root, 
            same_screen=True, child=xorg.X.NONE,
            root_x=0, root_y=0, event_x=0, event_y=0,
            state=0, detail=keycode
        )
        display.send_event(event, propagate=True)

_xorg.keyboard提供了X Window系统下的键盘事件监听和模拟接口,可以在Linux平台上监听、捕获以及模拟键盘事件。

监听和模拟键盘事件:

from pynput import _xorg
from pynput.keyboard import Controller, Key, Listener

def on_press(key):
    print('按下了 {0}'.format(key))

def on_release(key):
    if key == Key.esc:
        return False

keyboard = Controller()
with _xorg.Display():
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

    keyboard.press(Key.alt_l)
    keyboard.press('a')
    keyboard.release('a')
    keyboard.release(Key.alt_l)

3. _util

_util提供了一些常用的辅助函数和工具类,例如:鼠标轮询、键盘输入等。

在Linux系统下检测鼠标轮询:

from pynput._util import async

async def poll_mouse_input():
    while True:
        events = wmouse.get_events()
        for event in events:
            print('Mouse event:', event)
        await async.sleep(0.1)

_util.mouse提供了鼠标事件轮询和滚轮事件监听等功能,可以直接访问底层鼠标设备并捕获、模拟鼠标事件。

检测鼠标滚轮事件:

from pynput._util.mouse import WheelEncoder

class MyListener:
    def __init__(self):
        self.encoder = WheelEncoder()

    def on_scroll(self, dx, dy):
        self.encoder.step(dx, dy)

with Win32EventThread():
    listener = MyListener()
    hll = windll.LoadLibrary( 'User32.dll' )
    hll.SetWindowsHookExA.argtypes = [c_int,c_int,c_void_p,c_int]
    hll.SetWindowsHookExA.restype = c_void_p
    proc = WINFUNCTYPE(c_int, c_int, c_int, POINTER(c_void_p))(listener.encoder.hook_event)
    hhook = hll.SetWindowsHookExA(win32con.WH_MOUSE_LL, proc, hinst, 0)

_util.common提供了一些通用的工具函数,例如2D向量计算、时间相关函数等。

计算两个2D向量之间的距离:

from pynput._util.common import distance

print(distance((0, 0), (3, 4))) # 输出5.0

4. _keyboard

_keyboard是pynput的一个私有模块,提供了底层的键盘事件监听和模拟接口。使用该模块,你可以在Windows和Linux等操作系统平台下监听、捕获以及模拟键盘事件。以下代码演示了如何使用_keyboard模块监听用户按下键盘按钮:

from pynput import _win32 as win32
from pynput.keyboard import Key, Listener

def on_press(key):
    print('按下了 {0}'.format(key))

def on_release(key):
    if key == Key.esc:
        return False

with win32.EventThread():
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

5. _mac

_mac是pynput的一个私有模块,提供了访问macOS操作系统底层API的接口。使用该模块,你可以在macOS系统上监听、模拟并控制各种事件,例如:鼠标、键盘、Touch Bar等。以下代码演示了如何使用_mac模块模拟一个键盘输入事件:

from pynput._mac import uikit

def type_text(text):
    uikit.beep()
    uikit.type_string(text)

注意,使用_mac模块需要安装一些额外的依赖,详情请参见pynput · PyPI官方文档。

获取更多内容,请到pynput · PyPI查看

支持大佬!

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值