2

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'.

2

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

1

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.

2 Comments

Will not be able to listen to alphanumeric keys in Mac.
Why will it not be able to listen to alphanumeric keys?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.