【问题标题】:How to get the current Python interpreter path from inside a Python script? [duplicate]如何从 Python 脚本中获取当前的 Python 解释器路径? [复制]
【发布时间】:2011-08-21 02:55:36
【问题描述】:

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

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

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

我如何获得python_bin

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

【问题讨论】:

    标签: python path interpreter


    【解决方案1】:

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

    【讨论】:

    • 这对于嵌入式解释器不可靠,请使用 os.__file__ (感谢 stackoverflow.com/a/8187027/14420
    • 其实是os.__file__上方的一个目录
    • 有什么办法可以得到虚拟解释器的路径?
    【解决方案2】:

    我是通过以下方式找到的:

    >>> 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'
    

    【讨论】:

      【解决方案3】:

      只是为了确保:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 2013-12-11
        • 2018-04-13
        • 2013-08-03
        • 2019-12-20
        • 2010-10-10
        相关资源
        最近更新 更多