如何从Python脚本中获取当前的Python解释器路径?

e-s*_*tis 49 python interpreter path

我想用Python脚本运行Python脚本subprocess,我希望为每个脚本使用相同的解释器.

我正在使用virtualenv,所以我想做类似的事情:

subprocess.Popen('%s script.py' % python_bin)
Run Code Online (Sandbox Code Playgroud)

我怎么得到python_bin

它应该/usr/bin/python在virtualenv之外,并且/path/to/env/bin/python在virtualenv中.

Ign*_*ams 65

解释器的名称存储在变量sys.executable中

  • 对于嵌入式解释器来说这是不可靠的,使用`os .__ file__`(http://stackoverflow.com/a/8187027/14420提供) (10认同)

nem*_*emo 8

我找到了:

>>> 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'
Run Code Online (Sandbox Code Playgroud)


Yud*_*ira 5

只是为了确保:

>>> import sys
>>> sys.executable
'/usr/bin/python'
>>>
Run Code Online (Sandbox Code Playgroud)