Python键鼠输入模拟提速可行性:是否需切换至C#/Rust?
能否通过常规Python脚本提升键鼠输入模拟速度,还是必须切换至C#或Rust?
需求为实现游戏内毫秒级精度的移动模拟,以下是Python模拟移动的计划耗时与实际耗时对比分析:
| 计划耗时(秒) | 实际耗时(秒) | 操作 |
|---|---|---|
| 0.03125 | 0.0616778 | (key, w) |
| 0.34375 | 0.8544916 | (mouse, left) |
| 0.59375 | 1.3620928 | (key, space) |
| 0.625 | 1.4259067 | (mouse, left) |
| 0.703125 | 1.5822482 | (key, w) |
当前脚本使用keyboard和mouse库,核心代码如下:
def press_action(action, down): kind, key = action if kind == "key": if down: keyboard.press(key) else: keyboard.release(key) elif kind == "mouse": if down: mouse.press(button=key) else: mouse.release(button=key)
数据库存储的动作序列示例:
{'actions': [['mouse', 'left'], ['key', 'space'], ['key', 'shift']],
'duration_ms': 15.625}, {'actions': [['key', 'space'], ['key',
'shift']], 'duration_ms': 109.375}, {'actions': [['key', 'shift']],
'duration_ms': 31.25}]
重放动作序列的核心代码:
def replay_action_sequence(action_intervals): held = set() for step in action_intervals: # turn each action-list into a tuple, then build set current = { tuple(a) for a in step["actions"] } dur_s = step["duration_ms"] / 1000.0 for a in held - current: press_action(a, False) for a in current - held: press_action(a, True) held = current precise_sleep(dur_s) for a in held: press_action(a, False) def precise_sleep(seconds: float): """Sleep for `seconds`, busy‐wait last 1ms for accuracy.""" if seconds <= 0: return if seconds > 0.002: time.sleep(seconds - 0.001) end = time.perf_counter() + seconds while time.perf_counter() < end: pass
已尝试以下优化代码,但效果不明显:
try: windll.winmm.timeBeginPeriod(1) psutil.Process().nice(psutil.HIGH_PRIORITY_CLASS) except Exception: pass
本人为编程新手,更倾向于使用Python,若Python无法满足需求,考虑转用C#(有一定基础),请问C#脚本或其生成的.exe能否由Python调用?
内容的提问来源于stack exchange,提问作者StativBus
相关产品推荐
相关产品推荐

