Should I put #! (shebang) in Python scripts, and what form should it take?

前端 未结 12 1056
感动是毒
感动是毒 2020-11-22 01:27

Should I put the shebang in my Python scripts? In what form?

#!/usr/bin/env python 

or



        
12条回答
  •  遇见更好的自我
    2020-11-22 01:57

    If you have different modules installed and need to use a specific python install, then shebang appears to be limited at first. However, you can do tricks like the below to allow the shebang to be invoked first as a shell script and then choose python. This is very flexible imo:

    #!/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 $PREFERRED_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())
    

    Or better yet, perhaps, to facilitate code reuse across multiple python scripts:

    #!/bin/bash
    "true" '''\'; source $(cd $(dirname ${BASH_SOURCE[@]}) &>/dev/null && pwd)/select.sh; exec $CHOSEN_PYTHON "$0" "$@"; exit 127; '''
    

    and then select.sh has:

    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
        CHOSEN_PYTHON=$PREFERRED_PYTHON
    elif [ -x $ALTERNATIVE_PYTHON ]; then
        CHOSEN_PYTHON=$ALTERNATIVE_PYTHON
    else
        CHOSEN_PYTHON=$FALLBACK_PYTHON
    fi
    

提交回复
热议问题