I want to detect when I press the "space" bar key using python and pynput.
I tried their documentation, my old code but nothing works anymore on MacOS 15.1.1. Even running the script using sudo
, adding Visual Studio Code and Terminal app to the whitelist for Input Monitoring
and Accessibility
it still logs only the control and the command keys.
Here's the code I used (from the docs at https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-the-keyboard)
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()
After restarting my Mac it suddenly worked. So I guess using sudo + input monitoring permissions on IDE and terminal works fine :)