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

PythonPathInterpreter

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

I found it by:

>>> import sys           
>>> help(sys)
...

DATA
    __stderr__ = <open file '<stderr>', mode 'w' at 0x110029140>
    __stdin__ = <open file '<stdin>', mode 'r' at 0x110029030>
    __stdout__ = <open file '<stdout>', mode 'w' at 0x1100290b8>
    api_version = 1013
    argv = ['']
    builtin_module_names = ('__builtin__', '__main__', '_ast', '_codecs', ...
    byteorder = 'big'
    copyright = 'Copyright (c) 2001-2009 Python Software Foundati...ematis...
    dont_write_bytecode = False
    exc_value = TypeError('arg is a built-in module',)
    exec_prefix = '/usr/bin/../../opt/freeware'
    executable = '/usr/bin/python_64'

Solution 3 - Python

Just for making sure:

>>> import sys
>>> sys.executable
'/usr/bin/python'
>>>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questione-satisView Question on Stackoverflow
Solution 1 - PythonIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 2 - PythonnemoView Answer on Stackoverflow
Solution 3 - PythonYuda PrawiraView Answer on Stackoverflow