我如何从 Python 脚本中知道 Python 可执行文件的位置?

How do I know the location of the Python executable from within the Python script?

我正在编写一个名为 deploy.py 的脚本。

它需要知道 Python 可执行文件的位置。特别是首先用于调用脚本的 Python 可执行文件。原因是它会生成一个shell脚本。

这是我到目前为止一直在做的事情:

import sys

if __name__ == '__main__':
   executable = sys.argv[1]
   print executable

并将脚本称为 python deploy.py $(which python)。这行得通。有更好的方法吗?

当然,我是运行来自virtualenvPYTHONPATH 在 sys.environ 等中不起作用。

当前 Python 可执行文件的路径在 sys.executable:

import sys
print(sys.executable)

例如

PS C:\> py -c "import sys; print(sys.executable)"
C:\Python34\python.exe