Unable to run 'keyboard.is_pressed' on Mac

Viewed 9856

Im trying to make a script where every time I press x, it prints y.

When I run the code:

import keyboard

if keyboard.is_pressed('x'):
    print ("y")

The console outputs:

   raise OSError("Error 13 - Must be run as administrator")
OSError: Error 13 - Must be run as administrator

Thanks!

2 Answers

You can't run a script with virtual keyboard inputs like you regular python file in the macOS terminal due to a security feature.

Let's assume your filename is script.py.

If you type

python3 script.py

macOS would view this as a security breach as recording keyboard inputs (like keyboard.is_pressed('x')) is a typical method for recording someone's password as they type it in on a website, application, etc.


To prevent that error, you'd need to run the file as an administrator.

To do so, type:

sudo python3 script.py

It will ask you for your user's password and then proceed to execute the code.

The keyboard module registers global key events (they trigger without application focus) and this requires administrator permissions under MacOS.

Related