How do I run Python code as a script? [duplicate]

I need help running python in ubuntu

I can run python without a problem in my terminal but when I create a .py file I can't get it to run.


How it works (examples for python2, for python3, replace all occurrences of python by python3):

  1. python /path/to/script.py
    • works if file is either executable or not
    • shebang (#!/usr/bin/env python) in the head of the script is good practice, but not needed
  2. /path/to/script.py
    • works if script is executable
    • shebang is needed (#!/usr/bin/env python)
  3. script.py
    • works if script is in $PATH
    • script needs to be executable
    • filename needs to have extension
    • shebang is needed (#!/usr/bin/env python)
  4. script
    • works if script is in $PATH
    • script needs to be executable
    • filename should have no extension
    • shebang is needed (#!/usr/bin/env python)

A bit more information: precedence of command, shebang or extension?

The shell can get its information on how to run a script from two sources (in order of precedence):

  • The language information in the command: python <script>
  • The shebang, in the first line of the script: #!/usr/bin/env python

The language extension however does not play a role(!).

A few examples:

  1. A bash script, correct (language) information in the command, incorrect shebang, incorrect extension:

    #!/usr/bin/env python
    echo 'Monkey eats banana'
    

    ran with:

    $ sh /path/to/script.py
    > Monkey eats banana
    

    runs correctly, the information in the command takes precedence over both the shebang and the extension.

  2. An (executable) python script, ran with incorrect extension, but a correct shebang:

    #!/usr/bin/env/python
    print "Monkey eats banana"
    

    ran with:

    $ /path/to/script.sh
    > Monkey eats banana
    

    runs correctly, the information in the shebang takes precedence over the extension.

  3. An (executable) python script, with a correct extension, but without shebang (and without language information in the command):

    print "Monkey"
    

    Ran with the command:

    $ /path/to/script.py
    > Error: no such file "Monkey"
    

    does not run correctly, in spite of the language extension!


Probably you need to make it executable.

chmod +x /path/to/your/file.py

To run a python script, use python:

python script.py