Get path to original python executable (not the virtualenv)
Question:
Inside a virtualenv, sys.executable
gives /path/to/venv/bin/python
. How do I get the path of the python that the virtualenv was created from, such as /usr/bin/python3
?
For example,
$ cd /tmp
$ virtualenv -p /usr/bin/python3 venv
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /tmp/venv/bin/python3
Also creating executable in /tmp/venv/bin/python
Installing setuptools, pip, wheel...
done.
$ venv/bin/python -c 'import sys; print(sys.executable)'
/tmp/venv/bin/python
The answer that I want is /usr/bin/python3
.
Answers:
In a virtualenv, sys.real_prefix
is the directory of the actual Python installation being used by the virtualenv.
Other variables worth checking are sys.base_prefix
and sys.base_exec_prefix
.
Example code to run in virtualenv:
import sys
print(sys.base_prefix)
If you run python -m sysconfig
this will output the system configuration to the terminal. There you can see the BINDIR
variable.
Therefore you can programatically get this path as well as compute the executable path from within python with:
import sysconfig
from pathlib import Path
bin_dir = sysconfig.get_config_var("BINDIR")
executable_path = Path(bin_dir, "python")
Inside a virtualenv, sys.executable
gives /path/to/venv/bin/python
. How do I get the path of the python that the virtualenv was created from, such as /usr/bin/python3
?
For example,
$ cd /tmp
$ virtualenv -p /usr/bin/python3 venv
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /tmp/venv/bin/python3
Also creating executable in /tmp/venv/bin/python
Installing setuptools, pip, wheel...
done.
$ venv/bin/python -c 'import sys; print(sys.executable)'
/tmp/venv/bin/python
The answer that I want is /usr/bin/python3
.
In a virtualenv, sys.real_prefix
is the directory of the actual Python installation being used by the virtualenv.
Other variables worth checking are sys.base_prefix
and sys.base_exec_prefix
.
Example code to run in virtualenv:
import sys
print(sys.base_prefix)
If you run python -m sysconfig
this will output the system configuration to the terminal. There you can see the BINDIR
variable.
Therefore you can programatically get this path as well as compute the executable path from within python with:
import sysconfig
from pathlib import Path
bin_dir = sysconfig.get_config_var("BINDIR")
executable_path = Path(bin_dir, "python")