今天在用 pynput 的 Listener 和 Controller 对象时,发现无代码提示,写起来非常不舒服。
下面举例解决这个问题。
pynput 文档给的一个关于键盘 Controller 的示例代码是:
from pynput.keyboard import Key, Controller
keyboard = Controller()
# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)
# Type a lower case A; this will work even if no key on the
# physical keyboard is labelled 'A'
keyboard.press('a')
keyboard.release('a')
# Type two upper case As
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
keyboard.press('a')
keyboard.release('a')
# Type 'Hello World' using the shortcut type method
keyboard.type('Hello World')
只需要将导包语句改写成(Windows 用户):
from pynput.keyboard._win32 import Controller, Key
就可以正常弹出代码提示。(例如 keyboard.press())
pycharm 无法弹出代码提示的原因是:pynput 的内部代码使用了一招“偷梁换柱”,欺骗了 pycharm对keyboard的判断。