Skip to content Skip to sidebar Skip to footer

Stop Keyboard.record() Function At Any Keypress In Python

I found this keyboard module in Python which is used to log keyboard events (from what I got, mainly) using keyboard.record(), which takes in a string as a parameter, indicating at

Solution 1:

I don't see the point to using keyboard.record() if all you need it for is to stop at (and record) only the first keypress.

Instead, you could use keyboard.read_key() like this:

import keyboard
k = keyboard.read_key()  # in my python interpreter, this captures "enter up"
k = keyboard.read_key()  # so repeat the line if in the python interpreter

Solution 2:

After digging around in the source code, it looks like this is not possible.

defrecord(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

The parameter until is passed into wait(). Thus, wait() must have code to handle an arbitrary key press, which it does not.

defwait(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 isnotNone:
        hotkey_handler = add_hotkey(combination, unlock)
    wait()
    remove_hotkey(hotkey_handler)

Ultimately, there is no source code built to handle something like keyboard.record(until='any'), so you'll have to find a workaround. Consider checking How do I make python to wait for a pressed key. However, if you need to record the arbitrary key you would have used to stop the recording, then use J-L's workaround:

import keyboard
k = keyboard.read_key()  # in my python interpreter, this captures "enter up"
k = keyboard.read_key()  # so repeat the line if in the python interpreter

Solution 3:

You can make a function that sets a hook for all keys.

import keyboard

defrecord_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: passreturn recorded


record_until(any_key=True)

Post a Comment for "Stop Keyboard.record() Function At Any Keypress In Python"