为什么python鼠标模块中的duration属性完全关闭



我指的是python的mouse库。我使用mouse.move()来模拟将鼠标移动到(0, 0)的位置。该函数有一个duration*属性,它需要整数秒来模拟我的鼠标指针";"旅行";指向屏幕上的坐标。

import mouse
import time
before = time.monotonic()
mouse.move(0, 0, duration=2)
after = time.monotonic()
print(f"that took {after - before}")

在这种情况下,我将持续时间设置为2秒,但如果我们查看输出:that took 3.7649999998975545 seconds。我尝试了另一种情况,将持续时间设置为5秒,然后输出时间为:that took 9.327999999979511 seconds

有趣的是,当我以相同的持续时间重试时,我会得到相同的错误持续时间(因此在这种情况下,我多次重新运行duration=5,两次都得到9.327999999979511 seconds(。

为什么这么离谱?

链接到鼠标库。

mouse.move代码非常幼稚。与其实际检查经过的时间并补偿不精确的sleep持续时间,它只是假设所有sleep持续时间都是精确的,并且在sleep调用之外没有时间经过:

if duration:
start_x = position_x
start_y = position_y
dx = x - start_x
dy = y - start_y
if dx == 0 and dy == 0:
_time.sleep(duration)
else:
# 'steps_per_second' movements per second, default is 120.
# Round and keep float to ensure float division in Python 2
steps = max(1.0, float(int(duration * float(steps_per_second))))
for i in range(int(steps)+1):
move(start_x + dx*i/steps, start_y + dy*i/steps)
_time.sleep(duration/steps)

由于sleep的持续时间并不精确,因此该代码最终所花费的时间比预期的要长得多

最新更新