How to run code in python
Goal: Learn how to run a code in python.
The Python interpreter is usually installed as /usr/local/bin/python . Putting /usr/local/bin in your Unix shell's search path makes it possible to start it by typing the command:
python
You may be able to check where the python is installed by typing "which python".
(Note. In the same way you can start CDAT typing "cdat" at a command line).
You can put all your commands in a file with the extension 'file_name.py' and run it by
typing:
python file_name.py
Note that there is a difference between "python file" and "python <file". In the latter case, input requests from the program, such as calls to input() and raw_input(), are satisfied from file. Since this file has already been read until the end by the parser before the program starts executing, the program will encounter end-of-file immediately. In the former case (which is usually what you want) they are satisfied from whatever file or device is connected to standard input of the Python interpreter.
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i
before the script. (This does not work if the script is read from
standard input, for the same reason as explained in the previous
paragraph.)
Python scripts can be made directly executable, like shell scripts, by putting the line (assuming the python path as used in the example above)
#! /usr/local/bin/python
at the beginning of the script and giving the file an executable mode. The "#!" must be the first two characters of the file. On some platforms, this first line must end with a Unix-style line ending ("\n"), not a Mac OS ("\r") or Windows ("\r\n") line ending. Note that the hash, or pound, character, "#", is used to start a comment in Python.
The script can be given a executable mode, or permission, using the chmod command:
$ chmod +x myscript.py
For more on running python see online Python Tutorial.