I’m running a script successfully inside a virtual environment created with
(.venv) paul@desktop:~/st-python/clock-mpl$ python3 clock-4.py
I would like to run this script as a root inside the same virtual environment, but this doesn’t work:
(.venv) paul@desktop:~/st-python/clock-mpl$ sudo python3 clock-4.py
Traceback (most recent call last):
File "/home/paul/st-python/clock-mpl/clock-4.py", line 1, in <module>
import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib'
In sudo mode, Python is using different environment. Is there a workaround?
python3 referring to the same executable in both cases? (Try
which python3 and
sudo which python3) Probably not, since it’s a venv — you’ll need to call that one directly.
Sudo is not running the puthon3 in the venv.
Use the full path to the python3 in the venv.
This avoids the need to activate the venv.
Why does this happen? Do commands run “as” root with
sudo use a separate PATH for the root user, or something like that?
It depends on your configuration and what command-line options you
pass to your sudo invocation, but often yes. For example, on modern
Debian systems this is controlled by default with a secure_path
option in the /etc/sudoers file.