I have seen that many times these lines are used #!/usr/bin/python
and #!/usr/bin/env python
at the beginning of the scripts and I was wondering if there was any difference, if there is, which one is more recommended to use?
I have seen that many times these lines are used #!/usr/bin/python
and #!/usr/bin/env python
at the beginning of the scripts and I was wondering if there was any difference, if there is, which one is more recommended to use?
#!/usr/bin/env python
I would say that this is the most recommended as it makes use of the environment to look for the first occurrence of the Python executable. If you read the documentation for the command
env
:It is understood that you execute a command in a modified environment. Let's see what's in it
$PATH
:Then when using it
#!/usr/bin/env python
will search for the executable of the commandpython
according to the paths defined in$PATH
your environment, this is good since it is possible that you have several versions of Python installed (in Linux you usually have version 2 and 3).If we try this in the terminal (result may vary):
To demonstrate the operation of
env
we are going to do some tests. We create a symbolic link frompython3
a/usr/local/bin
:You can notice above that in my
$PATH
, the path/usr/local/bin
is before the path/usr/bin
so if I run again:Now I get version 3 of Python. Observe what happens if I modify the
$PATH
for test purposes:With
/usr/bin
as first route:With
/usr/local/bin
as first route:I hope this is clear, I think it is an advantage to use this way but sometimes it may not work as you expect if the Python paths have been manipulated, although it is also possible to be a bit more specific and use for example one of these in your script:
#!/usr/bin/env python2
#!/usr/bin/env python3
#!/usr/bin/python
This is also valid, you are simply calling the path of the Python executable:
I have run into some problems with this way, I seem to remember that in some Linux distributions the Python executable was not found in the
/usr/bin/python
.final notes
#!