I'm fiddling around with pynput for a personal project, and can't seem to get it working properly. It works perfectly with listening for keyboard and mouse input, but when I try update the mouse position to move it, nothing happens. This is the code I'm currently using to test it:
from pynput.mouse import Button, Controller, Listener
mouse = Controller()
class Mover:
def __init__(self, original_position=mouse.position):
self.original_position = original_position
def on_click(self, x, y, button, pressed):
if button == Button.left:
self.original_position = mouse.position # remember the position
print(mouse.position)
else:
mouse.position = self.original_position # return to position
print(mouse.position)
return False
mover = Mover()
with Listener(
on_click=mover.on_click
) as listener:
listener.join()
I'm running MacOS Monterey. Any help is much appreciated.
When running the above code, it prints out the mouse position as expected, but when right clicking, the mouse position does not update to original_position.
Per pynput
's page on Platform Limitations#macOS:
Recent versions of macOS restrict monitoring of the keyboard for security reasons. For that reason, one of the following must be true:
- The process must run as root.
- Your application must be white listed under Enable access for assistive devices. Note that this might require that you package your application, since otherwise the entire Python installation must be white listed.
- On versions after Mojave, you may also need to whitelist your terminal application if running your script from a terminal.
Per comments on the OP, the Python kernel was not whitelisted in System Preferences' Enable access for assistive devices section. Doing so resolved the reported issue.