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



我正在尝试编写一个简单的自动完成/热键脚本,该脚本将允许我键入SHIFT+K之类的内容,Python和Pynput将其转换为"尊敬的销售经理约翰·史密斯;。以下代码无限次地键入文本并使程序崩溃。如何确保文本只键入一次?请注意,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()
# 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()
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()

感谢大家提供的有益见解。这是我解决问题的办法。它监听最后键入的四个字符"k…";变成";向销售经理John Smith致以亲切的问候;。很明显,我可以添加任何我想要的文本字符串,并节省了很多写电子邮件的时间。

from pynput import keyboard
from pynput.keyboard import Controller, Listener, Key
c = Controller()
typed = []
tString = ""
message = "Kind Regards,nnJohn 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。

最新更新