为什么这些代码行会导致键盘滞后,还有其他选择吗?

Why are these lines of code causing keyboard lag and is there an alternative?

所以我正在学习 python 并且我正在尝试创建一个代码来检测在 Minecraft 中按下“space”和“a”之间的时间。问题是这个程序滞后于我的 keyboard/causes 键盘按下延迟。

我已将问题缩小为:

while True:
    if keyboard.is_pressed ('p'):
        strafe45()

如果我用这样的东西替换它:它不会导致键盘延迟。

run = 1
while run == 1:
    strafe45()

我认为这是因为第一个不断检查我是否正在输入 'p',这是延迟的原因,但我还能怎么写这样的东西呢?我不能使用 while 运行 == 1: 因为最终它会给我一个错误,因为我按住 'a' 并且变量 'start' 不再有赋值。

如果需要,这里是完整的代码:

import keyboard
import time
import math

def strafe45():
    while True:
        if keyboard.is_pressed ('space'):
            print ("starting timer")
            start = time.perf_counter()
            time.sleep(0.05)
        if keyboard.is_pressed ('a'):
            end = time.perf_counter()
            print ("ending timer")
            tickTime = end - start
            tick = 0.05
            if tickTime > tick:
                print ("Did not make strafe. Too slow by " + str(tickTime - tick) + "\n" +
                        "Time passed (r): " + str(round(tickTime/tick, 2)) + "\n" +
                        "Time passed (a): " + str(tickTime/tick))
                break
            if tickTime < tick:
                print ("Did make strafe by " + str(tick - tickTime) + "\n" +
                       "Time passed (r): " + str(round(tickTime/tick, 2)) + "\n" +
                       "Time passed (a): " + str(tickTime/tick))
                break

run = 1
while run == 1:
    strafe45()
"""while True:
    if keyboard.is_pressed ('p'):
        strafe45()"""

与其不断检查每个循环,不如添加一个钩子并仅在按下某个键时检查。 keyboard.on_press(callback) 为调用给定回调的每个键盘和键添加一个侦听器。这应该可以缓解您的延迟问题。查看 Keyboard API Page 以获得完整文档

def check_key(x): #x should be an keyboard.KeyboardEvent
    print x.name, x.scan_code, x.time

    if x.name == "":
        something

    elif x.name == "":
        something else

keyboard.on_press(check_key) 
while True:
    if keyboard.is_pressed ('p'):
        strafe45()

当按下 p 键时,会调用 strafe45,结果会发生一些 sleep 调用。

只要 p 不是 被按下,就会有一个紧密的 while 循环不断检查何时按下键。

你应该有一个 single while 循环, outside key-handling 函数,并确保一个time.sleep 每次通过此循环都会调用 - 通过明确地将其放入循环中。如果你调用函数来处理按键(一个好主意,因为代码变得更复杂),它们不应该有自己的循环——它们应该只是根据按下的内容对程序状态进行适当的更改。

例如:

begin = None
def begin_timing():
    global begin
    begin = time.perf_counter()

def end_timing():
    global begin
    if begin is not None: # otherwise, we weren't timing yet.
        end = time.perf_counter()
        print('elapsed time:', end - begin)
        begin = None # so that we can begin timing again.

while True:
    # There needs to be a delay each time through the loop,
    # but it needs to be considerably shorter than the time interval you're
    # trying to measure.
    time.sleep(0.01)
    if keyboard.is_pressed('b'): # begin
        begin_timing()
    elif keyboard.is_pressed('e'): # end
        end_timing()