我正在尝试通过键盘模块添加一个热键,该模块将根据所使用的热键调用具有不同参数的函数。为此,请使用python3键盘模块进行Iam。
我在这里查看文档:{{3}}
我希望我的程序始终处于while True循环中,等待不同的热键。
import keyboard
def hotkey_print(word):
print(word)
keyboard.add_hotkey('page up, page down', lambda: hotkey_print('did it work?'))
while True:
pass
我希望它能等待并打印出“它起作用了吗?”每次我按向上或向下键,但使用热键时什么也没有发生。
答案 0 :(得分:0)
根据pypi,键盘库的局限性之一是它应以root用户身份运行:
To avoid depending on X, the Linux parts reads raw device files (/dev/input/input*) but this requries root.
因此,您可以使用su -
并成为root用户,然后再次运行python文件,也可以使用其他库(如果有)。
编辑: 使用以下行代替无限循环:
# Block forever, like `while True`.
keyboard.wait()
答案 1 :(得分:0)
我遇到了同样的问题,并且对此感到厌烦... 只需使用pynput。 在这个模块中添加热键有很多不同的方法,但我只使用了我写的这段代码:
from pynput import keyboard
def startHotkeys():
if not "keysPressed" in globals():
globals()["keysPressed"] = list()
Thread(target=lambda: keyboard.Listener(on_press = recieveHotkey, on_release = removeHotkey).start()).start()
def recieveHotkey(inputKey):
if not inputKey in globals()["keysPressed"]:
globals()["keysPressed"].append(inputKey)
def removeHotkey(inputKey):
while inputKey in globals()["keysPressed"]:
globals()["keysPressed"].remove(inputKey)
def hotkey(key, toRun):
Thread(target=lambda:startHotkey(key, toRun)).start()
def startHotkey(keys, toRun):
if not "keysPressed" in globals():
globals()["keysPressed"] = list()
while True:
isPressed = len(globals()["keysPressed"]) > 0 #useful hack
if not isinstance(keys, list):
keys = [keys]
for i in keys:
if not i in globals()["keysPressed"]:
isPressed = False
break
if isPressed:
runCodeObj(toRun)
sleep(0.05)
def runCodeObj(code):
if isinstance(code, list):
for i in code:
if i:
i()
else:
if code:
code()
调用hotkey([keyboard.KeyCode(char="a"), keyboard.Key.Enter], lambda:print("you pressed enter and a at the same time"))
它永远不会停止(除非发生错误)
hotkey(keyboard.Key.ctrl, exit)
诸如此类... 您需要在程序开始时调用 startHotkeys()。