The Python Oracle

Purpose of #!/usr/bin/python3 shebang

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Track title: CC E Schuberts Piano Sonata D 784 in A

--

Chapters
00:00 Purpose Of #!/Usr/Bin/Python3 Shebang
01:03 Accepted Answer Score 400
02:14 Answer 2 Score 30
02:55 Answer 3 Score 14
03:47 Answer 4 Score 10
05:06 Answer 5 Score 7
05:30 Thank you

--

Full question
https://stackoverflow.com/questions/7670...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #scripting

#avk47



ACCEPTED ANSWER

Score 407


#!/usr/bin/python3 is a shebang line.

A shebang line defines where the interpreter is located. In this case, the python3 interpreter is located in /usr/bin/python3. A shebang line could also be a bash, ruby, perl or any other scripting languages' interpreter, for example: #!/bin/bash.

Without the shebang line, the operating system does not know it's a python script, even if you set the execution flag (chmod +x script.py) on the script and run it like ./script.py. To make the script run by default in python3, either invoke it as python3 script.py or set the shebang line.

You can use #!/usr/bin/env python3 for portability across different systems in case they have the language interpreter installed in different locations.




ANSWER 2

Score 30


That's called a hash-bang. If you run the script from the shell, it will inspect the first line to figure out what program should be started to interpret the script.

A non Unix based OS will use its own rules for figuring out how to run the script. Windows for example will use the filename extension and the # will cause the first line to be treated as a comment.

If the path to the Python executable is wrong, then naturally the script will fail. It is easy to create links to the actual executable from whatever location is specified by standard convention.




ANSWER 3

Score 14


This line helps find the program executable that will run the script. This shebang notation is fairly standard across most scripting languages (at least as used on grown-up operating systems).

An important aspect of this line is specifying which interpreter will be used. On many development-centered Linux distributions, for example, it is normal to have several versions of python installed at the same time.

Python 2.x and Python 3 are not 100% compatible, so this difference can be very important. So #! /usr/bin/python and #! /usr/bin/python3 are not the same (and neither are quite the same as #! /usr/bin/env python3 as noted elsewhere on this page.




ANSWER 4

Score 7


  1. And this line is how.

  2. It is ignored.

  3. It will fail to run, and should be changed to point to the proper location. Or env should be used.

  4. It will fail to run, and probably fail to run under a different version regardless.