简体   繁体   中英

Keyboard Listener for Mac using Python

I have tried all the codes for the keyboard listener. I had come across a post which said that Mac blocks the system to listen to the keyboard presses. I am using python. I am also using pynput as the library. How can I make Mac listen to my key presses? It only listens to special keys like 'Shift', 'Alt' and 'Command'.

This isn't a bug in pynput but a security feature of os x. You have to run Python as root to get around it.

sudo python3 app.py

If you don't want to keep using sudo the permanent fix is to go into the Security and Privacy preferences and add Python to the Accessibility tab.

From the docs:

Use pynput.keyboard.Listener like this:

 from pynput import keyboard 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() 

A keyboard listener is a threading.Thread, and all callbacks will be invoked from the thread.

Call pynput.keyboard.Listener.stop from anywhere, raise StopException or return False from a callback to stop the listener.

The key parameter passed to callbacks is a pynput.keyboard.Key, for special keys, a pynput.keyboard.KeyCode for normal alphanumeric keys, or just None for unknown keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM