Why do people write #!/usr/bin/env python on the first line of a Python script?

后端 未结 21 1719
刺人心
刺人心 2020-11-21 06:16

It seems to me like the files run the same without that line.

21条回答
  •  悲&欢浪女
    2020-11-21 07:18

    It allows you to select the executable that you wish to use; which is very handy if perhaps you have multiple python installs, and different modules in each and wish to choose. e.g.

    #!/bin/sh
    #
    # Choose the python we need. Explanation:
    # a) '''\' translates to \ in shell, and starts a python multi-line string
    # b) "" strings are treated as string concat by python, shell ignores them
    # c) "true" command ignores its arguments
    # c) exit before the ending ''' so the shell reads no further
    # d) reset set docstrings to ignore the multiline comment code
    #
    "true" '''\'
    PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
    ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
    FALLBACK_PYTHON=python3
    
    if [ -x $PREFERRED_PYTHON ]; then
        echo Using preferred python $ALTERNATIVE_PYTHON
        exec $PREFERRED_PYTHON "$0" "$@"
    elif [ -x $ALTERNATIVE_PYTHON ]; then
        echo Using alternative python $ALTERNATIVE_PYTHON
        exec $ALTERNATIVE_PYTHON "$0" "$@"
    else
        echo Using fallback python $FALLBACK_PYTHON
        exec python3 "$0" "$@"
    fi
    exit 127
    '''
    
    __doc__ = """What this file does"""
    print(__doc__)
    import platform
    print(platform.python_version())
    

提交回复
热议问题