The easiest way to use Python is with the interactive interpreter. Just like the UNIX shell, the interpreter allows you to execute one line at a time. This is an excellent way to test small blocks of code. The command python starts the interactive interpreter, and CTRL-D exits it. The interpreter prompts you to enter commands with “>>>”. In this chapter, examples starting with “>>>” show how the interpreter would respond to certain commands.
$ python >>> print "Hello, world" Hello, world >>> [CRTL-D] $
As you can see, the command print sends a line of text to standard output. It automatically adds a newline at the end of every line.
You can also use python to run commands that have been saved in a file. For example,
$ cat hello-script print "Hello, world" $ python hello-script Hello, world
To make a script that automatically uses python when it is run, add the line #!/usr/bin/ python (or whatever the path for python is on your system-use which python to find out) to the top of your file. This instructs the shell to use /usr/bin/python as the interpreter for the script. You will also need to make sure the file is executable, after which you can run the script by typing its name.
$ cat hello.py #!/usr/bin/python print "Hello, world" $ chmod u+x hello.py $ ./hello.py Hello, world
If the directory containing the script is not in your PATH, you will need to enter the pathname in order to run it. In the preceding example, ./hello.py was used to run a script in the current directory The extension .py indicates a Python script. Although it is not required, using .py when you name your Python scripts can help you organize your files.
The quickest way to execute a single command in Python is with the -c option. The command must be enclosed in single quotes, like this:
$ python -c 'print "Hello, world"' Hello, world