【问题标题】:Pynput listener for autocomplete / hotkey typing用于自动完成/热键输入的 Pynput 监听器
【发布时间】:2020-12-07 01:12:04
【问题描述】:

我正在尝试编写一个简单的自动完成/热键脚本,让我可以输入诸如 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()

【问题讨论】:

  • 这会引发异常......
  • 嗨内德,我试过你的代码,它对我来说很好,d.i。按“k”会为我输出一个“亲切的问候”。 Pessing SHIFT 将导致引发异常,因为 key.char 似乎只为字符键定义,而 SHIFT 不是。我是否误解了您的问题,或者您的脚本中有一些代码,但在发布的示例中没有?
  • 对我来说它输入了大约一百次。如何调整代码使其只输入一次?我正在使用上面代码块中的内容。
  • 在修复代码以捕获AttributeError 之后,它就可以工作了。你运行的是什么版本的 Python、pynput 和操作系统?
  • 正如 GordonAitchJays 的问题所暗示的,这可能是库、操作系统或 python 的某些特定版本的问题。它也可能与硬件有关。您是否尝试过在键盘或其他键盘上捕获不同的键?

标签: python pynput


【解决方案1】:
# 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()

【讨论】:

    【解决方案2】:
    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()
    

    【讨论】:

      【解决方案3】:

      感谢大家提供有用的见解。这是我对我的问题的解决方案。它侦听最后输入的四个字符。 “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。

      【讨论】:

        猜你喜欢
        • 2020-05-24
        • 2021-02-11
        • 2021-07-24
        • 2019-12-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 2020-12-15
        • 2020-09-23
        相关资源
        最近更新 更多