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.

Asked By: Hatshepsut

||

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)
Answered By: Ned Batchelder

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")
Answered By: Eugen_R
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.