-1

Okay I am new to Python, but my code does not run if the line

#!/usr/bin/python

is not present at the beginning of the file. Why is that ? What does it mean ? I thought it was used for to denote a python version if there were multiple versions installed.

#!/usr/bin/python
def main():
    a = [1,2,3]

    print a

if __name__ == "__main__":
  main()

Omitting the #!/usr/bin/python gives the following error only if I execute it using

./test.py on Ubuntu

if however I use the python command to run then it runs fine without the /usr/bin line.

Mureinik
  • 252,575
  • 45
  • 248
  • 283
Machina333
  • 603
  • 5
  • 13
  • you may run your file like "python test.py" in any *nix environment. The first line actually tells the shell how to execute the rest of the script. – Perpetualcoder Feb 10 '16 at 07:35
  • 1
    Related to http://stackoverflow.com/questions/2429511/why-do-people-write-usr-bin-env-python-on-the-first-line-of-a-python-script – Víctor M Feb 10 '16 at 07:38

3 Answers3

5

The first line of the script beginning with #! is a shebang (sometimes called a hash-bang).

The following executable path denotes which interpreter should be used to process the following code (in your case, /usr/bin/python).

If you run the script from the shell with python test.py, you don't need a shebang - the executable is python and the script is passed to it as an argument.

Joern Boegeholz
  • 425
  • 1
  • 7
  • 21
Mureinik
  • 252,575
  • 45
  • 248
  • 283
1

In Unix you can tell a file how it should be opened if it contains a script language (in your case Python).

This line is known as Shebang.

Víctor M
  • 307
  • 4
  • 15
jntme
  • 542
  • 1
  • 3
  • 17
0

./filename is used to run executable files, to execute it you need to specify the application required. Whereas, in using python filename.py you already specify the application to use that is python in this case.