I myself always use these lines many times #!/usr/bin/python
at the beginning of my python script , but I don't know why it is useful. I understand that if I execute in the terminal python script.py
it will not cause me problems if my script does not precede these lines.
Booting
#!
is called shebang and is a feature related to the use of Unix shells.The character
#
is a comment in many programming languages, notably Python, but in this case it is also the shell comment character .If you are going to run your program by putting:
you don't need that leading comment (which python will ignore anyway since it
#
also happens to be the python comment).But if on unix you give the file execute permission (with
chmod +x codigo.py
), then you can try to run it without specifying which interpreter to use, like so:In this case, the one that will try to execute the script is the shell that you are using (bash is the most common). The shell expects the script to be written in the shell language. If there was no shebang at the beginning, it would understand that what the file contains must be executed directly by the shell and this will obviously cause you errors because python code is not a shell language.
But if the file starts with shebang , then the shell uses that comment to know which interpreter to load to execute the rest of the file. In your case, by putting:
you are telling the shell to load the executable
python
from the path/usr/bin
and pass this file as a parameter.Beware , this is usually not the best option if you have multiple versions of python or virtual environments on your system. By using the shebang you are fixing which specific interpreter to use, so the execution by means
./codigo.py
may not be the same as bypython codigo.py
, since the first one would be using the default/usr/bin/python
as interpreter, while the second one would be using the versionpython
that appears first in the PATH.If you want to have the same flexibility in choosing which python to use, but using the shebang , what is usually put is:
This causes the shell to use as interpreter
/usr/bin/env
, passing it as parameterspython
and the name of the script in question. In this case the version ofpython
that will be executed will be determined by/usr/bin/env
, which will use thePATH
, so it would be the same as puttingpython
.