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

Asked

Viewed 1,195 times

12

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

#! /usr/bin/env python

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

#! /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 the production of more compatible and universally accepted code.

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

2 answers

12


The shebang #! /usr/bin/python when used will perform /usr/bin/python, while /usr/bin/env python will execute the Python according to the environment variable PATH that is, according to the system used.

The second way is advantageous and preferable if you have several versions of Python installed, because the env will ensure to run the interpreter according to the environment.

Another good reason to use it is due to 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 you find in the variable will be executed PATH.

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 in the environment variable is done only by the word python, even if not exactly, and if there are other entries containing it, the first in the list of PATH will be used.

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

Can also be useful in systems that may not have the same file organization structure.

So the first way gives more portability.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.