How does the root user locate executables?
A little while ago I was helping someone with running Python in a virtual environment, as root, for some specific purpose. I determined easily enough that this requires explicitly specifying the path to the virtual environment's Python executable (which to some extent defeats the purpose of the "virtual environment"); what I'm trying to understand is why.
When I activate a Python virtual environment (which modifies the PATH) and then try e.g.
sudo which python I get a different result from
which python (i.e. the Python that came with the OS install, rather than the one in the virtual environment); but
sudo echo $PATH gives the same result as
echo $PATH (i.e. the path to the virtual environment's
bin subdirectory is present, and precedes the system Python path). If I actually run Python, I can similarly verify from within Python that different installations are found this way.
I had understood that locating an executable involves looking in each directory in the
PATH environment variable, in order. I wouldn't be surprised if, say,
sudo had to open a new shell, re-initialize everything and thus fail to see the change to
PATH; but it clearly does see that change.
On my system,
which is explicitly documented to "... [do] this by searching the PATH for executable files matching the names of the arguments". That doesn't match the behaviour I see as root.
How is the root user locating the executable, and why is it different?