moses-palmer / pynput

Sends virtual input commands
GNU Lesser General Public License v3.0
1.73k stars 243 forks source link

[Looking for best practice:] How to design a transcription function with pynput? #569

Closed SpecialCharacter closed 8 months ago

SpecialCharacter commented 10 months ago

Description Not really a bug but more a request for best practice. I have two Listeners (on_press and on_release), so every input is doubled and I have to discard every second input (echo = True/False vs echo = chars). However, this seems to slow down the program. Is there any way to speed this up? Or is it the fact that the program has to go through the whole alphabet before it can accept new input? How to remediate? Should Quartz be imported immediately? (PS: I need two Listeners so I am aware when more than one key is pressed.)

Platform and pynput version MacOS Catalina 10.15.7 pynput version unknown

To Reproduce

# ====== Imports
from pynput import keyboard
from pynput.keyboard import Key, Controller

# --- globally initialise everything ---
echo = False

def on_press(key):
    global echo

def on_release(key):
    global echo

# R e t u r n s  the Unicode string associated with a Quartz keyboard event.
def darwin_intercept(event_type, event):                                    # pynput-internal definition
    import Quartz
    length, chars = Quartz.CGEventKeyboardGetUnicodeString(
        event, 1, None, None)

    if chars == 'A':
        if echo == False or echo == True:
            echo = chars
            Quartz.CGEventKeyboardSetUnicodeString(event, 1, 'G')        # Caesar's cypher (example)
        else:
            echo = False
            pass

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release,
        # Add suppressing events (darwin_intercept):
        darwin_intercept=darwin_intercept) as listener:
    listener.join()
moses-palmer commented 8 months ago

Thank you for your report.

As you note, this is not a bug report but rather a documentation request. I applied Python formatting to your example to be able to read it, but I am afraid that I cannot really make any sense of the code.

However, providing a value for darwin_intercept incurs no more overhead than calling that function, so I will hazard a guess that any slowdown you notice is caused by that code.

SpecialCharacter commented 8 months ago

Thank you for taking a look!

The question was if the "if echo ... else:" slows the process down (I have to suppress every second input because I have two listeners and so every input is doubled).

Edit: I have to do this for every character and punctuation, which I imagine slows the process down. Or can I put the "if echo ... else:" before all the if chars == ?