用于自动完成/热键输入的 Pynput 侦听器

Pynput listener for autocomplete / hotkey typing

我正在尝试编写一个简单的自动完成/热键脚本,它允许我键入诸如 SHIFT + K 之类的内容,Python 和 Pynput 将转换为“此致,John Smith,销售经理”。以下代码无限次键入文本并使程序崩溃。如何确保文本只输入一次?请注意 return Falsel.stop() 没有按预期工作,因为它们会导致脚本完成并退出。按一下热键应该会导致输入一个文本实例。脚本应该继续 运行 直到退出。

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

感谢大家提供有用的见解。这是我解决问题的方法。它监听最后输入的四个字符。 “k...”变为“Kind regards\n\nJohn Smith,销售经理”。显然,我可以添加任何我想要的文本字符串,从而节省大量编写电子邮件的时间。

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

我实际上没有意识到的一件事是,您需要在通过任务管理器调试 pynput 时关闭 Python。