问题描述
from pynput.keyboard import Key,Controller
keyboard = Controller()
s_key = input(str(" What leter do you want : "))
keyboard.press(s_key)
keyboard.release(s_key)
当我运行它时,它给了我一个错误,但是当我用 s_key
替换 Key.cmd
(对于 Windows 键)它可以工作,但是如果我在它要求的地方输入 Key.cmd
给我一个错误。我认为这是因为假设我输入了 key.cmd
,它要求它将它用引号括起来,所以它看起来像这样:
keyboard.press("Key.cmd")
keyboard.release("Key.cmd")
我看过它,我得出的结论是,当你有一个这样的变量时,它会用引号将它包装起来,我认为 pynput.keyboard
不会在引号中注册特殊键:
keyboard.press(Key.cmd)
keyboard.release(Key.cmd)
解决方法
试试这个:
from pynput.keyboard import Key,Controller
keyboard = Controller()
try:
s_key = getattr(Key,input("What letter do you want : ")) # get the key
except AttributeError:
print("no such key %s " % s_key) # if the key is not valid,notify the user about it
else: # if key is valid
keyboard.press(s_key)
keyboard.release(s_key)
您必须输入 cmd
而不是 Key.cmd
,因为如果您输入 Key.cmd
,此代码会尝试使用 Key.Key.cmd
,当然,它不会工作!