Basically I want to get a handle of the python interpreter so I can pass a script file to execute (from an external application).
-
4@Bhargav Rao: how can this question, which was asked 1 year before the question that it is supposed to be a duplicate of, be a duplicate of it? It's the other way around.mhawke– mhawke2016-10-27 22:58:17 +00:00Commented Oct 27, 2016 at 22:58
-
@mhawke The other had more views than this and was better worded. Hence I duped it in the reverse direction. TBH, Both of them does say the same thing, So we can even flag for merger.Bhargav Rao– Bhargav Rao2016-10-28 06:46:34 +00:00Commented Oct 28, 2016 at 6:46
-
3@BhargavRao: yes, it is better written and the title is probably responsible for that. Also the accepted answer is better and (now) includes a link to the documentation, so overall I think you're right.mhawke– mhawke2016-10-28 09:02:35 +00:00Commented Oct 28, 2016 at 9:02
3 Answers
This works in Linux & Windows:
Python 3.x
>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
Python 2.x
>>> import sys
>>> print sys.executable
/usr/bin/python
9 Comments
sys.executable is not reliable if working in an embedded python environment. My suggestions is to deduce it from
import os
os.__file__
8 Comments
pathlib.Path(os.__file__).parents[2] / 'bin' / 'python'sys.base_prefix and sys.prefix for the base python installation and virtual environment, respectively. This was convenient since I was already importing sys. More description in the docs.I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe
which gives this value on my machine:
C:\Python25\Python.exe
You just read the registry key to get the location.
However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.