Why do people write #!/usr/bin/env python on the first line of a Python script?

The #! shebang line at the top of a Python script specifies the path to the interpreter that should be used to run the script. The line #!/usr/bin/env python specifies that the Python interpreter should be used to run the script, regardless of the location of the Python executable on the system.

When the shebang line is present and the script is made executable, you can run the script by typing its name directly on the command line, without specifying the Python interpreter.

Watch a course Python - The Practical Guide

For example, if you have a script called myscript.py with the following shebang line:

#!/usr/bin/env python

You can make the script executable by running the following command:

chmod +x myscript.py

Then you can run the script by typing:

./myscript.py

This is convenient because it allows you to run the script without having to specify the Python interpreter each time.

The #!/usr/bin/env python shebang line is also portable, because it will use the Python interpreter that is installed as the default on the system, regardless of the specific path to the Python executable. This means that the script will run correctly on any system that has Python installed, as long as the shebang line is correct and the script is made executable.