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

前端 未结 12 1067
感动是毒
感动是毒 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 02:02

    Should I put the shebang in my Python scripts?

    Put a shebang into a Python script to indicate:

    • this module can be run as a script
    • whether it can be run only on python2, python3 or is it Python 2/3 compatible
    • on POSIX, it is necessary if you want to run the script directly without invoking python executable explicitly

    Are these equally portable? Which form is used most?

    If you write a shebang manually then always use #!/usr/bin/env python unless you have a specific reason not to use it. This form is understood even on Windows (Python launcher).

    Note: installed scripts should use a specific python executable e.g., /usr/bin/python or /home/me/.virtualenvs/project/bin/python. It is bad if some tool breaks if you activate a virtualenv in your shell. Luckily, the correct shebang is created automatically in most cases by setuptools or your distribution package tools (on Windows, setuptools can generate wrapper .exe scripts automatically).

    In other words, if the script is in a source checkout then you will probably see #!/usr/bin/env python. If it is installed then the shebang is a path to a specific python executable such as #!/usr/local/bin/python (NOTE: you should not write the paths from the latter category manually).

    To choose whether you should use python, python2, or python3 in the shebang, see PEP 394 - The "python" Command on Unix-Like Systems:

    • ... python should be used in the shebang line only for scripts that are source compatible with both Python 2 and 3.

    • in preparation for an eventual change in the default version of Python, Python 2 only scripts should either be updated to be source compatible with Python 3 or else to use python2 in the shebang line.

提交回复
热议问题