python录制鼠标键盘操作循环播放

依赖

pip install pynput

程序:

from pynput import mouse, keyboard
import time
import threading

# 用于存储录制的鼠标和键盘事件
mouse_events = []
keyboard_events = []

# 定义事件处理函数

# 处理鼠标事件
def on_move(x, y):
    mouse_events.append(('move', x, y))

def on_click(x, y, button, pressed):
    mouse_events.append(('click', x, y, button, pressed))

def on_scroll(x, y, dx, dy):
    mouse_events.append(('scroll', x, y, dx, dy))

# 处理键盘事件
def on_press(key):
    try:
        keyboard_events.append(('press', key.char))
    except AttributeError:
        keyboard_events.append(('press', str(key)))

def on_release(key):
    try:
        keyboard_events.append(('release', key.char))
    except AttributeError:
        keyboard_events.append(('release', str(key)))

    # 按下 Esc 键时停止监听
    if key == keyboard.Key.esc:
        return False

# 启动监听线程
def start_listening():
    # 启动鼠标和键盘的监听器
    mouse_listener = mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll)
    keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release)

    mouse_listener.start()
    keyboard_listener.start()

    # 等待监听器结束
    mouse_listener.join()
    keyboard_listener.join()

# 执行录制的操作
def replay_events():
    print("Replaying events...")
    for event in mouse_events:
        if event[0] == 'move':
            print(f"Moving mouse to {event[1]}, {event[2]}")
            # 在这里可以使用 `pyautogui.moveTo(x, y)` 等模拟鼠标移动
        elif event[0] == 'click':
            print(f"Clicking at {event[1]}, {event[2]} with button {event[3]} - {event[4]}")
            # 在这里可以使用 `pyautogui.click(x, y)` 等模拟鼠标点击
        elif event[0] == 'scroll':
            print(f"Scrolling at {event[1]}, {event[2]} with dx={event[3]} dy={event[4]}")
            # 在这里可以使用 `pyautogui.scroll(dx, dy)` 等模拟鼠标滚动

    for event in keyboard_events:
        if event[0] == 'press':
            print(f"Pressing key {event[1]}")
            # 在这里可以使用 `pyautogui.write()` 等模拟键盘按键
        elif event[0] == 'release':
            print(f"Releasing key {event[1]}")
            # 在这里可以模拟按键松开

    print("Replay finished.")

# 主程序
def main():
    print("Recording started, press 'Esc' key to stop recording.")
    
    # 启动监听线程
    listener_thread = threading.Thread(target=start_listening)
    listener_thread.start()

    # 等待用户按下 'Esc' 键结束录制
    listener_thread.join()

    # 录制结束后执行录制的操作
    replay_events()

    # 循环执行
    while True:
        print("Replaying recorded events...")
        replay_events()
        time.sleep(2)  # 延时 2 秒后重新执行

if __name__ == "__main__":
    main()
import pyautogui

# 在回放中使用 pyautogui
pyautogui.moveTo(x, y)  # 模拟鼠标移动
pyautogui.click(x, y)  # 模拟鼠标点击
pyautogui.write('Hello')  # 模拟键盘输入

你可能感兴趣的:(python,计算机外设,开发语言)