Search code examples
pythonpyenv

How to tell, from within a running script, what Python interpreter is running it?


I would like to output, in my script, the full path of the Python interpreter running it:

#!/usr/bin/env python

print("{}".format(full_path_of_interpreter_running_this_script)

The script is in the PATH and run as:

script.py

Can I do that? How?

Note: Doing which python or type python in bash does not help me, because I am using pyenv, and pyenv is doing shims magic.

Note: More than identifying the Python executable, I am interested in identifying the virtualenv that is being used, and I thought knowing the full path to the interpreter will help me in this.


Solution

  • This gives the full path to the command that was used to run the script:

    import sys
    print(sys.executable)