|I l@ve RuBoard|
So far, we've mostly talked about Python as a programming language. But it's also a software package called an interpreter . An interpreter is a kind of program that executes other programs. When you write Python programs, the Python interpreter reads your program, and carries out the instructions it contains. In this section we explore ways to tell the Python interpreter which programs to run.
 Technically, Python programs are first compiled (i.e., translated) to an intermediate form梑yte-code?which is then scanned by the Python interpreter. This byte-code compilation step is hidden and automatic, and makes Python faster than a pure interpreter.
When the Python package is installed on your machine, it generates a number of components. Depending on how you use it, the Python interpreter may take the form of an executable program, or a set of libraries linked into another program. In general, there are at least five ways to run programs through the Python interpreter:
As Python module files
As Unix-style script files
Embedded in another system
Platform-specific launching methods
Let's look at each of these strategies in turn.
Other Ways to Launch Python Programs
Caveat: to keep things simple, the description of using the interpreter in this chapter is fairly generic and stresses lowest-common-denominator ways to run Python programs (i.e., the command line, which works the same everywhere Python runs). For information on other ways to run Python on specific platforms, flip ahead to Appendix B. For instance, Python ports for MS-Windows and the Macintosh include graphical interfaces for editing and running code, which may be more to your taste.
Depending on your platform and background, you may also be interested in seeing a description of the new IDLE Integrated Development Environment for Python梐 graphical interface for editing, running, and debugging Python code that runs on any platform where Python's Tk support is installed (IDLE is a Python program that uses the Tkinter extension we'll meet in Part II).You can find this description in Appendix A. Emacs users can also find support at Python's web site for launching Python code in the Emacs environment; again, see Appendix A for details.
Perhaps the simplest way to run Python programs is to type them at Python's interactive command line. Assuming the interpreter is installed as an executable program on your system, typing python at your operating system's prompt without any arguments starts the interactive interpreter. For example:
% python >>> print 'Hello world!' Hello world! >>> lumberjack = "okay" >>> # Ctrl-D to exit (Ctrl-Z on some platforms)
Here python is typed at a Unix (or MS-DOS) prompt to begin an interactive Python session. Python prompts for input with >>> when it's waiting for you to type a new Python statement. When working interactively, the results of statements are displayed after the >>> lines. On most Unix machines, the two-key combination Ctrl-D (press the Ctrl key, then press D while Ctrl is held down) exits the interactive command-line and returns you to your operating system's command line; on MS-DOS and Windows systems, you may need to type Ctrl-Z to exit.
Now, we're not doing much in the previous example: we type Python print and assignment statements, which we'll study in detail later. But notice that the code we entered is executed immediately by the interpreter. For instance, after typing a print statement at the >>> prompt, the output (a Python string) is echoed back right away. There's no need to run the code through a compiler and linker first, as you'd normally do when using a language such as C or C++.
Because code is executed immediately, the interactive prompt turns out to be a handy place to experiment with the language, and we'll use it often in this part of the book to demonstrate small examples. In fact, this is the first rule of thumb: if you're ever in doubt about how a piece of Python code works, fire up the interactive command line and try it out. That's what it's there for.
The interactive prompt is also commonly used as a place to test the components of larger systems. As we'll see, the interactive command line lets us import components interactively and test their interfaces rapidly. Partly because of this interactive nature, Python supports an experimental and exploratory programming style you'll find convenient when starting out.
Although the interactive prompt is great for experimenting and testing, it has one big disadvantage: programs you type there go away as soon as the Python interpreter executes them. The code you type interactively is never stored in a file, so you can't run it again without retyping it from scratch. Cut-and-paste and command recall can help some here, but not much, especially when you start writing larger programs.
To save programs permanently, you need Python module files . Module files are simply text files containing Python statements. You can ask the Python interpreter to execute such a file by listing its name in a python command. As an example, suppose we start our favorite text editor and type two Python statements into a text file named spam.py:
import sys print sys.argv # more on this later
Again, we're ignoring the syntax of the statements in this file for now, so don't sweat the details; the point to notice is that we've typed code into a file, rather than at the interactive prompt. Once we've saved our text file, we can ask Python to run it by listing the filename as an argument on a python command in the operating system shell:
% python spam.py -i eggs -o bacon ['spam.py', '-i', 'eggs', '-o', 'bacon']
Notice that we called the module file spam.py; we could also call it simply spam, but for reasons we'll explain later, files of code we want to import into a client have to end with a .py suffix. We also listed four command-line arguments to be used by the Python program (the items after python spam.py); these are passed to the Python program, and are available through the name sys.argv, which works like the C argv array. By the way, if you're working on a Windows or MS-DOS platform, this example works the same, but the system prompt is normally different:
C:\book\tests> python spam.py -i eggs -o bacon ['spam.py', '-i', 'eggs', '-o', 'bacon']
So far, we've seen how to type code interactively and run files of code created with a text editor (modules). If you're going to use Python on a Unix, Linux, or Unix-like system, you can also turn files of Python code into executable programs, much as you would for programs coded in a shell language such as csh or ksh. Such files are usually called scripts; in simple terms, Unix-style scripts are just text files containing Python statements, but with two special properties:
Scripts usually start with a first line that begins with the characters #!, followed by the path to the Python interpreter on your machine.
Script files are usually marked as executable, to tell the operating system that they may be run as top-level programs. On Unix systems, a command such as chmod +x file.py usually does the trick.
Let's look at an example. Suppose we use our favorite text editor again, to create a file of Python code called brian:
#!/usr/local/bin/python print 'The Bright Side of Life...' # another comment here
We put the special line at the top of the file to tell the system where the Python interpreter lives. Technically, the first line is a Python comment. All comments in Python programs start with a # and span to the end of the line; they are a place to insert extra information for human readers of your code. But when a comment such as the first line in this file appears, it's special, since the operating system uses it to find an interpreter for running the program code in the rest of the file.
We also called this file simply brian, without the .py suffix we used for the module file earlier. Adding a .py to the name wouldn't hurt (and might help us remember that this is a Python program file); but since we don't plan on letting other modules import the code in this file, the name of the file is irrelevant. If we give our file executable privileges with a chmod +x brian shell command, we can run it from the operating system shell as though it were a binary program:
% brian The Bright Side of Life...
A note for Windows and MS-DOS users: the method described here is a Unix trick, and may not work on your platform. Not to worry: just use the module file technique from the previous section. List the file's name on an explicit python command line:
C:\book\tests> python brian The Bright Side of Life...
In this case, you don't need the special #! comment at the top (though Python just ignores it if it's present), and the file doesn't need to be given executable privileges. In fact, if you want to run files portably between Unix and MS-Windows, your life will probably be simpler if you always use the module file approach, not Unix-style scripts, to launch programs.
We've seen how to run code interactively, and how to launch module files and Unix-style scripts. That covers most of the cases we'll see in this book. But in some specialized domains, Python code may also be run by an enclosing system. In such cases, we say that Python programs are embedded in (i.e., run by) another program. The Python code itself may be entered into a text file, stored in a database, fetched from an HTML page, and so on. But from an operational perspective, another system梟ot you梞ay tell Python to run the code you've created.
For example, it's possible to create and run strings of Python code from a C program by calling functions in the Python runtime API (a set of services exported by the libraries created when Python is compiled on your machine):
#include <Python.h> . . . Py_Initialize(); PyRun_SimpleString("x = brave + sir + robin");
In this code snippet, a program coded in the C language (somefile.c) embeds the Python interpreter by linking in its libraries and passes it a Python assignment statement string to run. C programs may also gain access to Python objects, and process or execute them using other Python API tools.
This book isn't about Python/C integration, so we won't go into the details of what's really happening here. But you should be aware that, depending on how your organization plans to use Python, you may or may not be the one who actually starts the Python programs you create. Regardless, you can still use the interactive and file-based launching techniques described here, to test code in isolation from those enclosing systems that may eventually use it.
 See Programming Python for more details on embedding Python in C/C++.
Finally, depending on which type of computer you are using, there may be more specific ways to start Python programs than the general techniques we outlined above. For instance, on some Windows ports of Python, you may either run code from a Unix-like command-line interface, or by double-clicking on Python program icons. And on Macintosh ports, you may be able to drag Python program icons to the interpreter's icon, to make program files execute. We'll have more to say about platform-specific details like this in an appendix to this book.
With all these options and commands, it's easy for beginners to be confused about which command is entered at which prompt. Here's a quick summary:
The Python interpreter is usually started from the system's command line:
Programs may be typed at Python's interactive interpreter command line:
>>> print X
Programs may also be typed into text files, using your favorite text editor:
Unix-style script files are started from the system shell:
Module files are run from the system shell:
% python spam.py
When Python is embedded, Python code may be entered in arbitrary ways.
|I l@ve RuBoard|