[英]Pynput listener for autocomplete / hotkey typing
我正在尝试编写一个简单的自动完成/热键脚本,它允许我输入诸如 SHIFT + K 之类的内容,Python 和 Pynput 会将其转换为“亲切的问候,约翰史密斯,销售经理”。 以下代码无限次键入文本并导致程序崩溃。 如何确保文本只输入一次? 请注意, return False
和l.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...”变成“亲切的问候\\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。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.