首页 > 解决方案 > 如何在mac上使用python添加热键处理程序?

问题描述

我正在使用 macos Mojave10.14 和 python3.7.4 我尝试使用以下代码添加热键处理程序。但是失败了。第一个代码是。

import keyboard
import time
def g_hotkey_process():
    print('g pressed!')
def main():
    print('hello keyboard!!')
    keyboard.add_hotkey('g', g_hotkey_process)
if __name__ == '__main__':
    main() 
    while(True):
        print('...') 
        time.sleep(3)  

第二个代码是。

from pynput import keyboard

print('hello key!dfsdf')
def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

两种情况,都不能捕获按键。以上示例在 Windows 上运行良好。谁能知道这个解决方案?

标签: pythonmacoskeyboardpynput

解决方案


推荐阅读