Consider the following script run in a Python 3.x virtual environment on Windows 10:
#!/usr/bin/env python
import sys, os, subprocess
print(sys.executable)
args = ["python", "-c", "import sys; print(sys.executable)"]
p = subprocess.Popen(args, stdout=None, env=os.environ)
p.wait()
On most systems, the two calls to print(sys.executable)
return a string showing the location of python.exe within the virtual environment, e.g.
C:> python test.py
C:\venv\Scripts\python.exe
C:\venv\Scripts\python.exe
But occasionally, we'll encounter a machine where the first call finds python.exe from the virtual environment, but the second call finds python.exe from the machine's global installation, e.g.
C:> python test.py
C:\venv\Scripts\python.exe
C:\Users\me\AppData\Local\Programs\Python\Python38\python.exe
The program above is simplified to make it easy to read. The real program uses subprocess.popen to call another python script whose imports fail because the global install doesn't have the same packages as the virtual install.
I suspected the PATH environment variable, but it appears to be the same when printed before and during the subprocess.popen call. In both cases, the venv/Scripts folder exists ahead of the global Python install folder.
I've also tried deleting the virtual environment and recreating it. No luck.