You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python通过WebSocket控制鼠标移动失败问题求助

问题分析与解决方案

核心问题

  1. 类型不匹配:WebSocket接收的消息是字符串,你直接将拆分后的字符串传入mouse.move(),但该函数需要整数/浮点数类型的坐标,字符串参数会被库忽略,导致鼠标无响应。
  2. 冗余的分片逻辑:针对"X;Y"格式的消息,拆分后直接取列表的前两个元素即可,无需复杂的分片操作,当前逻辑反而容易出错。

修正后的代码

import asyncio
import websockets
import mouse

async def handler(websocket):
    while True:
        try:
            messageWS = await websocket.recv()
            # 拆分消息为X、Y字符串
            x_str, y_str = messageWS.split(';')
            # 转换为整数类型并去除可能的空格
            x = int(x_str.strip())
            y = int(y_str.strip())
            # 移动鼠标到目标绝对坐标
            mouse.move(x, y)
        except ValueError:
            print("错误:接收到的坐标不是有效数字")
        except Exception as e:
            print(f"发生异常:{e}")
            break

start_server = websockets.serve(handler, "localhost", 3000)
print("WS up!")

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

额外建议

  • 如果需要相对当前位置移动鼠标,可以添加absolute=False参数:mouse.move(x, y, absolute=False)。
  • 可以增加屏幕坐标范围校验,避免传入超出屏幕显示区域的无效数值(可通过mouse.get_position()获取当前屏幕的尺寸参考)。

内容的提问来源于stack exchange,提问作者User825613

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:06:13