If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the Python interpreter that lives inside virtualenv's bin/
directory:
import subprocess
# Path to a Python interpreter that runs any Python script
# under the virtualenv /path/to/virtualenv/
python_bin = "/path/to/virtualenv/bin/python"
# Path to the script that must run under the virtualenv
script_file = "must/run/under/virtualenv/script.py"
subprocess.Popen([python_bin, script_file])
However, if you want to activate the virtualenv under the current Python interpreter instead of a subprocess, you can call exec
passing the activate_this.py
script, like this:
# Doing exec() on this file will alter the current interpreter's
# environment so you can import libraries in the virtualenv
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
exec(open(activate_this_file).read(), {'__file__': activate_this_file})
Note that you need to use the virtualenv library, not venv, for the above.
If you use venv, you can copy the implementation of virtualenv's activate_this.py, it should still more or less work with venv with just a few minor changes.