How to get the current Python interpreter path from inside a Python script?

28,197

The name of the interpreter is stored in the variable sys.executable

Share:
28,197
e-satis
Author by

e-satis

French Python/Django freelance dev. I love training people all around the world. You can contact me for a session via Formations Python. Got some famous answers about Python decorators, metaclasses and yield, and this :

Updated on July 09, 2022

Comments

  • e-satis
    e-satis almost 2 years

    I want to run a Python script from a Python script with subprocess, and I wish to do it using the same interpreter for each of them.

    I'm using virtualenv, so I'd like to do something like:

    subprocess.Popen('%s script.py' % python_bin)
    

    How do I get python_bin?

    It should be /usr/bin/python outside a virtualenv, and /path/to/env/bin/python in a virtualenv.

  • matt wilkie
    matt wilkie over 11 years
    this isn't reliable for embedded interpreters, use os.__file__ for that (courtesy of stackoverflow.com/a/8187027/14420)
  • denfromufa
    denfromufa over 8 years
    it is actually one directory above os.__file__
  • Shravya Boggarapu
    Shravya Boggarapu over 4 years
    Any way to get the path for the virtual interpreter?