moses-palmer / pynput

Sends virtual input commands
GNU Lesser General Public License v3.0
1.79k stars 248 forks source link

Mouse/keyboard input silently fails on macOS if the current process isn't a trusted accessibility client #389

Closed drmfinlay closed 3 years ago

drmfinlay commented 3 years ago

Description If accessibility access has not been granted for the application that runs Python (e.g. Terminal), pynput will silently fail to simulate mouse and keyboard input. This will only happen if accessibility access is revoked after the first time you get the system dialogue box prompting you to allow it for the application.

Platform and pynput version macOS version 11.2.3 and pynput version 1.7.3.

To Reproduce

  1. Navigate to the macOS preferences screen for apps allowed to control your computer: System Preferences -> Security & Privacy -> Privacy (tab) -> Accessibility (section).
  2. Find and uncheck the application in the list that runs the Python process, if it is checked.
  3. Start a Python interpreter.
  4. Try to simulate mouse or keyboard input with pynput:
from pynput.keyboard import Key, Controller

keyboard = Controller()

# Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)

Possible Solution I wonder if the relevant classes for macOS should be adjusted to emit a one-time warning message in this case? The AXIsProcessTrusted() function could be used to check if the current process is a trusted accessibility client:

import HIServices

if not HIServices.AXIsProcessTrusted():
    print("This process is NOT a trusted accessibility client, so pynput will not "
          "function properly. Please grant accessibility access for this app in "
          "System Preferences.")
moses-palmer commented 3 years ago

Thank you for your suggestion!

I have added code to check for this, and an additional flag IS_TRUSTED on Listener instances. I have pushed the changes to the master branch, but no released version includes this change yet.

drmfinlay commented 3 years ago

Thank you for adding a check for this and for all your work on this splendid library!