Difference from #! in the first line of a Python script

9

For a Python script to be run on a Linux / Unix-based operating system, it should start with the designated shebang ( #! ):

#! /usr/bin/env python

But followed by the same I've seen two different instructions used:

#! /usr/bin/env python

and

#! /usr/bin/python

This leaves a bit of confusion between both methods to declare the file as a script , and the disambiguation of this subject seems relevant to producing more compatible and universally accepted code.

What are the differences between the stated methods, their advantages and disadvantages, in an attempt to determine which should be used?

    
asked by anonymous 09.04.2015 / 21:15

2 answers

9

Shebang #! /usr/bin/python will run /usr/bin/python , while /usr/bin/env python will run the Python according to the environment variable PATH ie according to the system used.

The second form is advantageous and preferable if you have multiple versions of Python installed, since env will guarantee run the interpreter according to the environment.

Another good reason to use it is because of portability , you can run a script in different environments without worrying about the location of the interpreter.

The disadvantage of /usr/bin/env python is that the first interpreter it encounters in the variable PATH will be executed.

    
09.04.2015 / 21:49
4

The first looks at the environment variable PATH looking for python to know where the installed Python is running. The second is a specific location.

The search for the environment variable is done only by the word python , even if not exactly, and if there are other entries that contain it, the first one in the PATH list will be used.

Obviously the first one can be more reliable when you know that you or different users can use different versions of Python.

It can also be useful on systems that may not have the same file organization structure.

So the first form gives more portability.

    
09.04.2015 / 21:49