rootsudopython-venvadafruitneopixel

Neopixel library can not be run in a virtual environment in python (requires sudo) for raspberry pi


Is it possible for the Adafruit neopixel library to have root access to a raspberry pi 4b, whilst not being in a virtual environment to control WS2812B leds. I have downloaded the adafruit module in the venv, however, it is not installed in python3 or thonny. It seems awfully hard to download external modules, which can not have root access or then work without sudo (controlling GPIO pins). Thank you, from a new pi user.

- cd my_project
$ sudo python -m venv env
$ source env/bin/activate
(env) $
python3 -m pip install rpi_ws281x adafruit-circuitpython-neopixel
python3 -m pip install --force-reinstall adafruit-blinka
#sudo thonny - did not work and neither did venv in thonny work
sudo python
>>>import board
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'board'
>>> import neopixel
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'neopixel'

Background info: Using this library apparently has two constraints: it has to be run in Python 3, and it has to be run as root. The documentation explains that "For NeoPixels to work on Raspberry Pi, you must run the code as root! Root access is required to access the RPi peripherals."

How can I deconflict that pi will not give root access to external modules, which the neopixel requires and venv won't allow.


Solution

  • A python virtual environment is identified by environment variables. When you use sudo, you are discarding your local environment, so in general a virtual environment doesn't survive the privilege transition.

    You can explicitly ask sudo to preserve certain environment variables with the --preserve-env option, like this:

    sudo --preserve-env=VIRTUAL_ENV,PATH
    

    For example:

    $ python -m venv env
    $ . env/bin/activate
    (env) $ pip install rpi_ws281x adafruit-circuitpython-neopixel
    (env) $ sudo  --preserve-env=PATH,VIRTUAL_ENV python
    Python 3.11.6 (main, Oct  3 2023, 00:00:00) [GCC 13.2.1 20230728 (Red Hat 13.2.1-1)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import rpi_ws281x
    >>> rpi_ws281x.WS2811_SUCCESS
    0
    

    It is possible to configure your Pi so that you don't need root permission to access GPIO devices using the gpio unix group.