Search code examples
python-3.xmqttrootsudopaho

Import Error when running paho mqtt as root (sudo python3 filename.py)


I'm about to set up a Raspberry Pi 3+ Model A as a client for openHAB2. Here I have a sensor on the Pi and WS2812b (alias Neopixel) connected.

Now I wrote (my first script) in Python to publish the sensor data (Bosch BMP280) via paho mqtt to the broker. This works as desired when I start the Python file with "python3 filename.py" ...

If I want to start the same file with "sudo python3 filename.py" the following error message appears:

 Traceback (most recent call last):
   File "mqtt_client.py", line 15, in <module>
     import paho.mqtt.client as mqtt
ModuleNotFoundError: No module named 'paho'

However, I would like to extend the script to use the WS2812b. To control the WS2812b, the script must be started with root privileges. So I do not understand why paho-mqtt is no longer known when running "sudo" ...

Does anyone have a solution for this? Many thanks!


Solution

  • When you are running your script using sudo python3 filename.py it is using a python environment different from the one you used to install Paho.

    In order to fix this you can either:

    • Add Defaults env_keep += "PYTHONPATH" to your /etc/sudoers
    • Run your script using sudo /path/to/python pythonscript.py