I'm sure that while working on your Raspberry Pi you have had to execute commands in a Terminal with the sudo prefix because they required root privileges. If you ever need to run a Python script that is in a virtual environment as root, you must use the full path to your virtual environment's Python interpreter.
Simply prefixing sudo before python, as shown in the following example, does not work under most circumstances, even if we are in the virtual environment. The sudo action will use the default Python that's available to the root user, as shown in the second half of the example:
# Won't work as you might expect!
(venv) $ sudo python my_script.py
# Here is what the root user uses as 'python' (which is actually Python version 2).
(venv) $ sudo which python
/usr/bin/python
The correct way to run a script as root is to pass the absolute path to your virtual environment's Python interpreter. We can find the absolute path using the which python command from inside an activated virtual environment:
(venv) $ which python
/home/pi/pyiot/chapter01/venv/bin/python
Now, we sudo our virtual environment's Python interpreter and the script will run as the root user and within the content of our virtual environment:
(venv) $ sudo /home/pi/pyiot/chapter01/venv/bin/python my_script.py
Next, we'll see how to run a Python script that's sandboxed in a virtual environment from outside of its virtual environment.