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?
Is 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.
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.