Python通过WebSocket控制鼠标移动失败问题求助
问题分析与解决方案
核心问题
- 类型不匹配:WebSocket接收的消息是字符串,你直接将拆分后的字符串传入
mouse.move(),但该函数需要整数/浮点数类型的坐标,字符串参数会被库忽略,导致鼠标无响应。 - 冗余的分片逻辑:针对"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
相关产品推荐
相关产品推荐

