简体   繁体   中英

Pynput listener for autocomplete / hotkey typing

I am attempting to write a simple autocomplete / hotkeys script that will allow me to type things like SHIFT + K, which Python and Pynput will convert to "Kind regards, John Smith, Sales Manager". The following code types the text an infinite number of times and crashes the program. How can I ensure that the text is typed only one time? Note that return False and l.stop() do not work as intended because they cause the script to complete and exit. One press of the hot keys should result in one instance of the text getting typed. The script should continue running until exited.

from pynput import keyboard
from pynput.keyboard import Controller, Listener
c = Controller()

def press_callback(key):
    if key.char == 'k':
        c.type("Kind regards")

l = Listener(on_press=press_callback)

l.start()
l.join()
from pynput import keyboard, Controller

def on_activate():
    '''Defines what happens on press of the hotkey'''
    keyboard.type('Kind regards, John Smith, Sales Manager.')

def for_canonical(hotkey):
    '''Removes any modifier state from the key events 
    and normalises modifiers with more than one physical button'''
    return lambda k: hotkey(keyboard.Listener.canonical(k))

'''Creating the hotkey'''
hotkey = keyboard.HotKey(
keyboard.HotKey.parse('<shift>+k'), 
on_activate)

with keyboard.Listener(
        on_press=for_canonical(hotkey.press),
        on_release=for_canonical(hotkey.release)) as 
listener:
    listener.join()
# solution is based on the example on https://pypi.org/project/pynput/, Global hotkeys

from pynput.keyboard import Controller, Listener, HotKey, Key

c = Controller()


def press_callback():
    try:
        c.release(Key.shift)  # update - undo the shift, otherwise all type will be Uppercase
        c.press(Key.backspace)  # update - Undo the K of the shift-k
        c.type("Kind regards ")
    except AttributeError:
        pass


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


hk = HotKey(HotKey.parse('<shift>+k'), on_activate=press_callback)

with Listener(on_press=for_canonical(hk.press), on_release=for_canonical(hk.release)) as l:
    l.join()

Thanks everyone for your helpful insights. Here is my solution to my problem. It listens for the last four characters typed. "k..." becomes "Kind regards\\n\\nJohn Smith, Sales Manager". Obviously I can add whatever text strings I want and save a lot of time writing emails.

from pynput import keyboard
from pynput.keyboard import Controller, Listener, Key

c = Controller()

typed = []
tString = ""
message = "Kind Regards,\n\nJohn Smith, Sales Manager"

def press_callback(key):
    if hasattr(key,'char'):
        for letter in "abcdefghijklmnopqrstuvwxyz.":
            if key.char == letter:
                typed.append(letter)
                if len(typed)>4:
                    typed.pop(0)
                tString = ','.join(typed).replace(',','')
                print(tString)
                if tString == "k...":
                    for _ in range(4):
                        c.press(Key.backspace)
                        c.release(Key.backspace) 
                    c.type(message)

l = Listener(on_press=press_callback)

l.start()
l.join()

And one thing I actually failed to realise is that you need to shut down Python while debugging pynput through the task manager.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM