在Python中的任何按键停止keyboard.record()函数

问题描述:

我在Python中发现这个keyboard模块,它用于使用keyboard.record()来记录键盘事件(主要来自我所得到的),它接受字符串作为参数,功能应该停止。在Python中的任何按键停止keyboard.record()函数

所以我的问题是..有什么办法让功能停止在任何按键?据我所知,该模块没有特别的关键字可以指示这样的事情。

就像我试着这样做

keys_pressed = keyboard.record(until='any')

但是,这导致错误。

+0

如果您希望记录器在任何按键停止,我不确定为什么你想要它在第一位。顺便说一下,模块生成的事件类型是_key down_和_key up_。此外,该问题也应包含错误。 – CristiFati

我没有看到使用keyboard.record()的要点,如果你需要的只是停下来(和记录)只有第一个按键。

相反,你可以使用keyboard.read_key()这样的:

​​
+0

感谢您的建议! 'read_key()'在这里完美工作。 –

在源代码周围挖掘后,看起来这是不可能的。

def record(until='escape'): 
    """ 
    Records all keyboard events from all keyboards until the user presses the 
    given key combination. Then returns the list of events recorded, of type 
    `keyboard.KeyboardEvent`. Pairs well with 
    `play(events)`. 

    Note: this is a blocking function. 
    Note: for more details on the keyboard hook and events see `hook`. 
    """ 
    recorded = [] 
    hook(recorded.append) 
    wait(until) 
    unhook(recorded.append) 
    return recorded 

参数until传递到wait()。因此,wait()必须有代码来处理任意按键,而不是。

def wait(combination=None): 
    """ 
    Blocks the program execution until the given key combination is pressed or, 
    if given no parameters, blocks forever. 
    """ 
    wait, unlock = _make_wait_and_unlock() 
    if combination is not None: 
     hotkey_handler = add_hotkey(combination, unlock) 
    wait() 
    remove_hotkey(hotkey_handler) 

最终,有用来处理像keyboard.record(until='any')没有源代码,所以你必须找到一个解决办法。考虑检查How do I make python to wait for a pressed key。然而,如果你需要记录你会用来停止录制任意键,然后用Ĵ-L的解决方法:

​​
+0

是的,我应该在询问之前自己绕过源代码。无论如何,'read_key()'似乎对我正在尝试做的事很好,谢谢你的答案。 –

可以作出这样的规定,为所有键挂机的功能。

import keyboard 

def record_until(any_key=False): 
    recorded = [] 

    keyboard.hook(recorded.append) # need this to capture terminator 

    wait, unlock = keyboard._make_wait_and_unlock() 

    if any_key: 
     hook = keyboard.hook(unlock) 

    wait() 

    try: 
     keyboard.remove_hotkey(hook) 
    except ValueError: pass 

    return recorded 


record_until(any_key=True)