It seems to me like the files run the same without that line.
It's recommended way, proposed in documentation:
2.2.2. Executable Python Scripts
On BSD’ish Unix systems, Python scripts can be made directly executable, like shell scripts, by putting the line
#! /usr/bin/env python3.2
from http://docs.python.org/py3k/tutorial/interpreter.html#executable-python-scripts
That is called the shebang line. As the Wikipedia entry explains:
In computing, a shebang (also called a hashbang, hashpling, pound bang, or crunchbang) refers to the characters "#!" when they are the first two characters in an interpreter directive as the first line of a text file. In a Unix-like operating system, the program loader takes the presence of these two characters as an indication that the file is a script, and tries to execute that script using the interpreter specified by the rest of the first line in the file.
See also the Unix FAQ entry.
Even on Windows, where the shebang line does not determine the interpreter to be run, you can pass options to the interpreter by specifying them on the shebang line. I find it useful to keep a generic shebang line in one-off scripts (such as the ones I write when answering questions on SO), so I can quickly test them on both Windows and ArchLinux.
The env utility allows you to invoke a command on the path:
The first remaining argument specifies the program name to invoke; it is searched for according to the
PATH
environment variable. Any remaining arguments are passed as arguments to that program.
If you're running your script in a virtual environment, say venv
, then executing which python
while working on venv
will display the path to the Python interpreter:
~/Envs/venv/bin/python
Note that the name of the virtual environment is embedded in the path to the Python interpreter. Therefore, hardcoding this path in your script will cause two problems:
Therefore, to add to Jonathan's answer, the ideal shebang is #!/usr/bin/env python
, not just for portability across OSes but for portability across virtual environments as well!
It tells the interpreter which version of python to run the program with when you have multiple versions of python.
This is a shell convention that tells the shell which program can execute the script.
#!/usr/bin/env python
resolves to a path to the Python binary.
You can try this issue using virtualenv
Here is test.py
#! /usr/bin/env python
import sys
print(sys.version)
Create virtual environments
virtualenv test2.6 -p /usr/bin/python2.6
virtualenv test2.7 -p /usr/bin/python2.7
activate each environment then check the differences
echo $PATH
./test.py