Find full path of the Python interpreter?

前端 未结 3 1034
执念已碎
执念已碎 2020-11-22 15:40

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

相关标签:
3条回答
  • 2020-11-22 16:36

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

    import sys
    
    print(sys.executable)
    

    which is now documented here

    0 讨论(0)
  • 2020-11-22 16:36

    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
    
    0 讨论(0)
  • 2020-11-22 16:37

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

    If you are not sure of the actual path of the python command and is available in your system, Use the following command.

    pi@osboxes:~ $ which python
    /usr/bin/python
    pi@osboxes:~ $ readlink -f $(which python)
    /usr/bin/python2.7
    pi@osboxes:~ $ 
    pi@osboxes:~ $ which python3
    /usr/bin/python3
    pi@osboxes:~ $ 
    pi@osboxes:~ $ readlink -f $(which python3)
    /usr/bin/python3.7
    pi@osboxes:~ $ 
    
    0 讨论(0)
提交回复
热议问题