I am running the Debian lite cli PI 3 I have a wired USB mouse I have plugged into one of 4 usb ports I am trying to write a python script to detect when I left/right click and use the scroll wheel.

Core question : How do I detect mouse clicks on the raspberry pi with only the cli (I do not want the mouse to interact with the cli, just, for now, to print something to the console)

I have tried pynput but when running import pynput I get the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/pi/.local/lib/python2.7/site-packages/pynput/__init__.py", line 40, in <module>
    from . import keyboard
  File "/home/pi/.local/lib/python2.7/site-packages/pynput/keyboard/__init__.py", line 31, in <module>
    backend = backend(__name__)
  File "/home/pi/.local/lib/python2.7/site-packages/pynput/_util/__init__.py", line 82, in backend
    if resolutions else '')
ImportError: this platform is not supported: ('failed to acquire X connection: Bad display name ""', DisplayNameError())

Try one of the following resolutions:

 * Please make sure that you have an X server running, and that the DISPLAY environment variable is set correctly


1 Does this mean that pynput is not compatible with the rpi?
2 Or have I done something wrong?
3 Is pynput the thing to use? (I just need to detect the mouse)
  • Error message says it needs a running X server (default on Linux) which is not running on 'lite'. See the docs at pynput.readthedocs.io/en/latest. And this is not a Pi specific question
    – Dirk
    Oct 28, 2021 at 6:52

1 Answer 1


Install the desktop environment (the full Pi OS, not the "Lite" one), then you'll be able to use pynput.

Otherwise, use an input library which supports mice and don't require X, e.g. SDL. Here's a tutorial for making a small game with PySDL2, which shows how to process SDL events. You'll have to add SDL_MouseButtonEvent to the event loop.

  • I am unable to access the bit bucket link (bitbucket.org/marcusva/py-sdl2/downloads ),its a 404. Is there an alternate download or can I install it with pip?
    – creare
    Oct 28, 2021 at 13:36
  • @creare I assume installing it with pip would work. Another option is apt-get install python3-sdl2 (assuming you're using Python 3) Oct 29, 2021 at 12:24

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.