Should I put the shebang in my Python scripts? In what form?
#!/usr/bin/env python
or
Should I put the shebang in my Python scripts?
Put a shebang into a Python script to indicate:
python
executable explicitlyAre 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.