what shebang to use for python scripts run under a pyenv virtualenv

前端 未结 5 1748
攒了一身酷
攒了一身酷 2020-12-08 18:34

When a python script is supposed to be run from a pyenv virtualenv what is the correct shebang for the file?

As an example test case, the d

5条回答
  •  一向
    一向 (楼主)
    2020-12-08 18:45

    It's not exactly answering the Q, but this suggestion by ephiement I think is a much better way to do what you want. I've elaborated a bit and added some more of an explanation as to how this works and how you can dynamically select the python to use:

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

提交回复
热议问题