问题:查找Python解释器的完整路径?

如何从当前执行的Python脚本中找到当前运行的Python解释器的完整路径?

How do I find the full path of the currently running Python interpreter from within the currently executing Python script?


回答 0

sys.executable 包含当前运行的Python解释器的完整路径。

import sys

print(sys.executable)

现在记录在这里

sys.executable contains full path of the currently running Python interpreter.

import sys

print(sys.executable)

which is now documented here


回答 1

只是使用os.environ以下方法来指出有用性的另一种方式:

import os
python_executable_path = os.environ['_']

例如

$ python -c "import os; print(os.environ['_'])"
/usr/bin/python

Just noting a different way of questionable usefulness, using os.environ:

import os
python_executable_path = os.environ['_']

e.g.

$ python -c "import os; print(os.environ['_'])"
/usr/bin/python

回答 2

有几种其他方法可以找出Linux中当前使用的python:1)which python命令。2)command -v python命令3)type python命令

同样,在Windows上使用Cygwin也会得到相同的结果。

kuvivek@HOSTNAME ~
$ which python
/usr/bin/python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3

kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

如果您已经在python shell中。尝试任何这些。注意:这是另一种方法。不是最好的pythonic方法。

>>>
>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>

There are a few alternate ways to figure out the currently used python in Linux is: 1) which python command. 2) command -v python command 3) type python command

Similarly On Windows with Cygwin will also result the same.

kuvivek@HOSTNAME ~
$ which python
/usr/bin/python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3

kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.

>>>
>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。