[Python] Inconsistent behavior with pynput when creating global hotkey

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create a program that copies a certain text with the shortcut ctrl + c, and through that same hotkey, activates a logic that will perform certain formatting actions in the string. The code I managed to get so far is this:

    import pyperclip
    import pynput


    def clipboard_proccer():
    print('into proccer')
    current_value = pyperclip.paste()
    current_value = current_value.replace('\n','')
    current_value = current_value.replace('\r', '')
    pyperclip.copy(current_value)
    print('out of proccer')

    def for_canonical(f):
    return lambda k: f(l.canonical(k))

    if __name__ == '__main__':
    hotkey = pynput.keyboard.HotKey(pynput.keyboard.HotKey.parse('<ctrl>+c'), clipboard_proccer)
    with pynput.keyboard.Listener(on_press=for_canonical(hotkey.press), on_release=for_canonical(hotkey.release)) as l:
    l.join()


    As you can see, the idea is to remove all instances of \n and \r from the string, then put that back into the clipboard using pyperclip. To activate that function when pressing ctrl + c, I'm using pynput.

    The thing is, it works, but only once. The first time, it does exactly what I want it to: copy the text, then immediately after do the formatting, however after that, it never copies again through ctrl + c, but it continues printing the two print functions inside clipboard_proccer. Interestingly, if I copy some text through the context menu (ie right mouse button), and then press ctrl + c, it executes the formatting.

    What am I doing wrong? How can I achieve what I want every time, instead of just the first time.

    Continue reading...

Compartilhe esta Página