Chapter 3. How You Run Programs

Okay, it’s time to start running some code. Now that you have a handle on program execution, you’re finally ready to start some real Python programming. At this point, we’ll assume that you have Python installed on your computer; if not, see Appendix A for installation and configuration hints.

There are a variety of ways to tell Python to execute the code you type. This chapter discusses all the program launching techniques in common use today. Along the way, you’ll learn both how to type code interactively, and save it in files to be run with command lines, Unix tricks, icon clicks, IDEs, imports, and more.

If you just want to find out how to run a Python program quickly, you may be tempted to just read the parts that pertain to your platform and move on to Chapter 4. But don’t skip the material on module imports, since that’s essential to understanding Python’s architecture. And we encourage you to at least skim the sections on IDLE and other IDEs, so you know what tools are available once you start developing more sophisticated Python programs.

Interactive Coding

Perhaps the simplest way to run Python programs is to type them at Python’s interactive command line. There are a variety of ways to start this command line—in an IDE, from a system console, and so on. Assuming the interpreter is installed as an executable program on your system, the most platform-neutral way to start an interactive interpreter session is usually to type just “python” at your operating system’s prompt, without any arguments. For example:

% python
Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Here the word “python” is typed at your system shell prompt, to begin an interactive Python session (the “%” character stands for your system’s prompt, not your input). The notion of a system shell prompt is generic, but varies per platform:

  • On Windows, you can type python in a DOS console window (a.k.a. Command Prompt), or the Start/Run... dialog box.

  • On Unix and Linux, you might type this in a shell window (e.g., in an xterm or console, running a shell such as ksh or csh).

  • Other systems may use similar or platform-specific devices. On PalmPilots, for example, click the Python home icon to launch an interactive session; on a Zaurus PDA, open a Terminal window.

If you have not set your shell’s PATH environment variable to include Python, you may need to replace the word “python” with the full path to the Python executable on your machine. For instance, on Windows, try typing C:Python22python (or C:Python23python for Version 2.3); on Unix and Linux, /usr/local/bin/python (or /usr/bin/python) will often suffice.

Once the Python interactive session starts, it begins by printing two lines of informational text (which we normally omit in our examples to save space), and prompts for input with >>> when it’s waiting for you to type a new Python statement or expression. When working interactively, the results of your code are displayed after the >>> lines—here are the results of two Python print statements:

% python
>>> print 'Hello world!'
Hello world!
>>> print 2 ** 8
256

Again, don’t worry about the details of the print statements shown here yet (we’ll start digging into syntax in the next chapter). In short, they print a Python string and an integer, as shown by the output lines that appear after each >>> input line.

When working interactively like this, we can type as many Python commands as we like; each is run immediately after entered. Moreover, because the interactive session automatically prints the results of expressions typed, we don’t usually need to say “print” explicitly at this prompt:

>>> lumberjack = 'okay'   
>>> lumberjack
'okay'
>>> 2 ** 8
256
>>>                      use Ctrl-D or Ctrl-Z to exit
%

Here, the last two lines typed are expressions (lumberjack and 2 ** 8), and their results are displayed automatically. To exit an interactive session like this one and return to your system shell prompt, type Ctrl-D on Unix-like machines; on MS-DOS and Windows systems, type Ctrl-Z to exit. In the IDLE GUI discussed later, either type Ctrl-D, or simply close the window.

Now, we’re not doing much in this session’s code: we type Python print and assignment statements, and a few expressions, which we’ll study in detail later. The main thing to notice is that the code entered is executed immediately by the interpreter, when the Enter key is pressed at the end of the line.

For instance, after typing the first 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++. As you’ll see in later chapters, you can also run multiline statements at the interactive prompt; the statement runs immediately after you’ve entered all its lines.

Besides typing python in a shell window, you can also begin similar interactive sessions by starting IDLE’s main window, or on Windows via the Start button menus for Python and select the Python (command-line) menu option as shown in Figure 2-1. Both spawn a >>> prompt with equivalent functionality—code is run as it is typed.

Using the Interactive Prompt

Although simple to use, there are a few ways that the interactive prompt seems to trip up beginners:

  • Type Python commands only. First of all, remember that you can only type Python code at the Python prompt, not system commands. There are ways to run system commands from within Python code (e.g., os.system), but they are not as direct as simply typing the command itself.

  • Print statements are required only in files. Because the interactive interpreter automatically prints the results of expressions, you do not need to type complete print statements interactively. This is a nice feature, but tends to confuse users when they move on to writing code in files: within a code file, you really must use print statements to see your output, because expression results are not automatically echoed. You must say print in files, but not interactively.

  • Don’t indent at the interactive prompt (yet). When typing Python programs, either interactively or into a text file, be sure to start all your unnested statements in column 1 (that is, all the way to the left). If you don’t, Python may print a “SyntaxError” message. Until Chapter 9, all statements will be unnested, so this includes everything for now. This seems to be a recurring confusion in introductory Python classes. A leading space generates an error message.

  • Prompts and compound statements. We won’t meet compound (multiline) statements until Chapter 9 , but as a preview, you should know that when typing lines two and beyond of a compound statement interactively, the prompt may change. In the simple shell window interface, the interactive prompt changes to ... instead of >>> for lines 2 and beyond; in the IDLE interface, lines after the first are automatically indented. In either case, a blank line (hitting the Enter key at the start of a line) is needed to tell interactive Python that you’re done typing the multiline statement; by contrast, blank lines are ignored in files.

    You’ll see why this matters in Chapter 9. For now, if you happen to come across a ... prompt or blank line when entering your code, it probably means that you’ve somehow confused interactive Python into thinking you’re typing a multiline statement. Try hitting the Enter key, or a Ctrl-C combination to get back to the main prompt. The >>> and ... prompts can also be changed (they are available in built-in module sys), but we’ll assume they have not been in our examples.

System Command Lines and Files

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 cut and paste code from an interactive session, you have to edit out Python prompts, program outputs, and so on.

To save programs permanently, you need to write your code in files, usually known as modules. Modules are simply text files containing Python statements. Once coded, you can ask the Python interpreter to execute the statements in such a file any number of times, and in a variety of ways—by system command lines, by file icon clicks, by options in the IDLE user interface, and more. However they are run, Python executes all the code in a module file from top to bottom, each time you run the file. Such files are often referred to as programs in Python—a series of precoded statements.

The next few sections explore ways to run code typed into module files. In this section we run files in the most basic way: by listing their names in a python command line entered at a system prompt. As a first example, suppose we start our favorite text editor (e.g., vi, notepad, or the IDLE editor) and type three Python statements into a text file named spam.py:

print 2 ** 8                              # Raise to a power.
print 'the bright side ' + 'of life'      # + means concatenation.

This file contains two Python print statements and Python comments to the right. Text after a # is simply ignored as a human-readable comment, and is not part of the statement’s syntax. Again, ignore the syntax of code in this file for now. The point to notice is that we’ve typed code into a file, rather than at the interactive prompt. In the process, we’ve coded a fully-functional Python script.

Once we’ve saved this text file, we can ask Python to run it by listing its full filename as a first argument on a python command, typed at the system shell’s prompt:

% python spam.py
256
the bright side of life

Here again, you will type such a system shell command in whatever your system provides for command-line entry—a DOS console window, an xterm, or similar. Remember to replace “python” with a full directory path if your PATH setting is not configured. The output of this little script shows up after the command is typed—it’s the result of the two print statements in the text file.

Notice that the module file is called spam.py. As for all top-level files, it could also be called simply spam, but files of code we want to import into a client have to end with a .py suffix. We’ll study imports later in this chapter. Because you may want to import a file in the future, it’s a good idea to use .py suffixes for most Python files that you code. Some text editors also detect Python files by their .py suffix; if the suffix is not present, you may not get things like syntax colorization and automatic indentation.

Because this scheme uses shell command lines to start Python programs, all the usual shell syntax applies. For instance, we can route the output of a Python script to a file in order to save it, by using special shell syntax:

% python spam.py > saveit.txt

In this case, the two output lines shown in the prior run show up in file saveit.txt, instead of being printed. This is generally known as stream redirection ; it works for both input and output text, and works on both Windows and Unix-like systems. It also has little to do with Python (Python simply supports it), so we will skip further details on redirection here.

If you are working on a Windows or MS-DOS platform, this example works the same, but the system prompt is normally different:

C:Python22>python spam.py
256
the bright side of life

As usual, be sure to type the full path to Python if you haven’t set your PATH environment variable:

D:	emp>C:python22python spam.py
256
the bright side of life

(On some versions of Windows, you can also type just the name of your script, regardless of the directory you work in. Because newer Windows systems use the Windows registry to find a program with which to run a file, you don’t need to list it on the command line explicitly.)

Finally, remember to give the full path to your script file if it lives a different directory than the one you are working in. For example, the following system command line, run from D:other, assumes Python is on your system path, but runs a file located elsewhere:

D:other>python c:codemyscript.py

Using Command Lines and Files

Running program files from system command lines is also a fairly straightforward launch option, especially if you are familiar with command lines in general from prior Unix or DOS work. Here are a few pointers about common beginner traps before moving on:

  • Beware of automatic extensions on Windows. If you use the Notepad program to code program files on Windows, be careful to pick type All Files when it comes time to save your file, and give your file a .py suffix explicitly. Otherwise, Notepad saves your file with a “.txt” extension (e.g., as spam.py.txt), making it difficult to run in some launching schemes.

    Worse, Windows hides file extensions by default unless you have changed your view options, so you may not even notice that you’ve coded a text file, not a Python file. The file’s icon may give this away—if it’s not a snake, you may have trouble. Un-colored code in IDLE and files that open to edit instead of run when clicked are other symptoms of this problem.

    MS Word similarly adds a .doc extension by default; much worse, it adds formatting characters that are not legal Python syntax. As a rule of thumb, always pick All Files when saving under Windows, or use more programmer-friendly text editors such as IDLE. IDLE does not even add a .py suffix automatically—a feature programmers like, and users do not.

  • Use file extensions at system prompts, but not imports. Don’t forget to type the full name of your file in system command lines, that is, use python spam.py. This differs from Python import statements we’ll meet later in this chapter, which omit both the .py file suffix, and directory path: import spam. This may seem simple, but it’s a common mistake.

    At the system prompt, you are in a system shell, not Python, so Python’s module file search rules do not apply. Because of that, you must give the .py extension, and can optionally include a full directory path leading to the file you wish to run. For instance, to run a file that resides in a different directory than the one you are working in, you will typically list its full path name (C:python22>python d: estsspam.py). Within Python code, you say just import spam, and rely on the Python module search path to locate your file.

  • Use print statements in files. Yes, this was already mentioned in the prior section, but it is so important that it should be said again here. Unlike interactive coding, you generally must use print statements to see output from program files.

Unix Executable Scripts (#!)

If you are 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 executable scripts; in simple terms, Unix-style executable scripts are just normal text files containing Python statements, but with two special properties:

  • Their first line is special. Scripts usually start with a first line that begins with the characters #! (often called “hash bang”) followed by the path to the Python interpreter on your machine.

  • They usually have executable privileges. 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 a 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

The special line at the top of the file tells the system where the Python interpreter lives. Technically, the first line is a Python comment. As mentioned earlier, 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.

Also, this file is called simply brian, without the .py suffix 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 the 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 users: the method described here is a Unix trick, and may not work on your platform. Not to worry; just use the basic command-line technique explored earlier. List the file’s name on an explicit python command line:[1]

C:ook	ests> python brian
The Bright Side of Life...

In this case, you don’t need the special #! comment at the top (although 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 basic command-line approach, not Unix-style scripts, to launch programs.

Clicking Windows File Icons

On Windows, Python automatically registers itself to be the program that opens Python program files when they are clicked. Because of that, it is possible to launch the Python programs you write by simply clicking (or double-clicking) on their file icons with your mouse.

On Windows, icon clicks are made easy by the Windows registry. On non-Windows systems, you will probably be able to perform a similar trick, but the icons, file explorer, navigation schemes, and more may differ slightly. On some Unix systems, for instance, you may need to register the .py extension with your file explorer GUI, make your script executable using the #! trick of the prior section, or associate the file MIME type with an application or command by editing files, installing programs, or using other tools. See your file explorer’s documentation for more details, if clicks do not work correctly right off the bat.

Clicking Icons on Windows

To illustrate, suppose we create the following program file with our text editor, and save it as filename script4.py:

# A comment
import sys
print sys.platform
print 2 ** 100

There’s not much new here—just an import and two prints again (sys.platform is just a string that identifies the kind of computer you’re working on; it lives in a module called sys, which we must import to load). In fact, we can run this file from a system command line:

D:OldVaioLP-2ndEdExamples>c:python22python script4.py
win32
1267650600228229401496703205376

Icon clicks allow us to run this file without any typing at all. If we find this file’s icon—for instance, by selecting My Computer, and working our way down on the D drive—we will get the file explorer picture captured in Figure 3-1 and shown on Windows XP. Python source files show up as snakes on Windows, and byte code files as snakes with eyes closed (or with a reddish color in Version 2.3). You will normally want to click (or otherwise run) the source code file, in order to pick up your most recent changes. To launch the file here, simply click on the icon for script4.py.

Python file icons on Windows
Figure 3-1. Python file icons on Windows

The raw_input Trick

Unfortunately, on Windows, the result of clicking on file icons may not be incredibly satisfying. In fact, as is, this example script generates a perplexing “flash” when clicked—not the sort of feedback that budding Python programmers usually hope for! This is not a bug, but has to do with the way the Windows port handles printed output.

By default, Python generates a pop-up black DOS console window to serve as a clicked file’s input and output. If a script prints and exits, then, well, it just prints and exits—the console window appears, and text is printed there, but the console window closes and disappears on program exit. Unless you are very fast or your machine is very slow, you won’t get to see your output at all. Although this is normal behavior, it’s probably not what you had in mind.

Luckily, it’s easy to work around this. If you need your script’s output to stick around when launched with clicks, simply put a call to the built-in raw_input function at the very bottom of your script. For example:

# A comment
import sys
print sys.platform
print 2 ** 100
raw_input(  )             # ADDED

In general, raw_input reads the next line of standard input, and waits if there is none yet available. The net effect in this context will be to pause the script, thereby keeping the output window shown in Figure 3-2 open, until we press the Enter key.

Clicked program output with raw_input
Figure 3-2. Clicked program output with raw_input

Now that we’ve shown you this trick, keep in mind that it is usually only required for Windows, and then only if your script prints text and exits, and only if you will launch this script by clicking its file icon. You should only add this call to the bottom of your top-level files, if and only if all of these three conditions apply. There is no reason to add this call in any other contexts.[2]

Before moving ahead, note that the raw_input call applied here is the input counterpart of using the print statement for outputs. It is the simplest way to read user input, and is more general than this example implies. For instance, raw_input:

  • Optionally accepts a string that will be printed as a prompt (e.g., raw_input('Press Enter to exit'))

  • Returns to your script the line of text read as a string (e.g., nextinput = raw_input( ))

  • Supports input stream redirections at the system shell level (e.g., python spam.py < input.txt), just as the print statement does for output.

We’ll use raw_input in more advanced ways later in this text; see Chapter 10 for an example of using it in an interactive loop.

Other Icon Click Limitations

Even with the raw_input trick, clicking file icons is not without its perils. You also may not get to see Python error messages. If your script generates an error, the error message text is written to the pop-up console window—which then immediately disappears as before. Worse, adding a raw_input call to your file will not help this time, because your script will likely abort long before it reaches this call. In other words, you won’t be able to tell what went wrong.

Because of these limitations, it is probably best to view icon clicks as a way to launch programs after they have been debugged. Especially when starting out, use other techniques, such as system command lines and IDLE (later in this chapter), so that you can see generated error messages, and view your normal output without resorting to coding tricks. When we meet exceptions later in this book, we’ll also learn that it is possible to intercept and recover from errors, so that they do not terminate our programs. Watch for the discussion of the try statement later in this book for an alternative way to keep the console window from closing on errors.

Module Imports and Reloads

So far, we’ve been calling files of code “modules,” and using the word “import,” without explaining what these terms mean. We’ll study modules and larger program architecture in depth in Part V. Because imports are also a way to launch programs, this section introduces enough module basics to get you started.

In simple terms, every file of Python code whose name ends in a .py extension is a module. Other files can access the items defined by a module by importing that module; import operations essentially load another file, and grant access to the file’s contents. Furthermore, the contents of a module are made available to the outside world through its attributes , a term we’ll define next.

This module-based services model turns out to be the core idea behind program architecture in Python. Larger programs usually take the form of multiple module files, which import tools from other module files. One of the modules is designated as the main or top-level file, and is the one launched to start the entire program.

We’ll delve into such architecture issues in more detail later in this book. This chapter is mostly interested in the fact that import operations run the code in a file that is being loaded, as a final step. Because of this, importing a file is yet another way to launch it.

For instance, if we start an interactive session (in IDLE, from a command line, or otherwise), we can run the original script4.py file that appeared earlier with a simple import:

D:LP-2ndEdExamples>c:python22python
>>> import script4
win32
1267650600228229401496703205376

This works, but only once per session (really, process), by default. After the first import, later imports do nothing, even if we change and save the module’s source file again in another window:

>>> import script4
>>> import script4

This is by design; imports are too expensive an operation to repeat more than once per program run. As we’ll learn in Chapter 15, imports must find files, compile to byte code, and run the code. If we really want to force Python to rerun the file again in the same session (without stopping and restarting the session), we need to instead call the built-in reload function:

>>> reload(script4)
win32
65536
<module 'script4' from 'script4.py'>
>>>

The reload function loads and runs the current version of your file’s code, if you’ve changed it in another window. This allows you to edit and pick up new code on the fly, within the current Python interactive session. In this session, for example, the second print statement in script4.py was changed in another window to print 2 ** 16, between the time of the first import and the reload call.

The reload function expects the name of an already-loaded module object, so you have to have successfully imported once, before you reload. Notice that reload also expects parenthesis around the module object name, whereas import does not—reload is a function that is called, and import is a statement. That’s why we must pass the module name as an argument in parenthesis, and is why we get back an extra output line when reloading. The last output line is just the print representation of the reload call’s return value, a Python module object. More on functions in Chapter 12.

The Grander Module Story: Attributes

Imports and reloads provide a natural program launch option, because files are executed by import operations as a last step. In the broader scheme of things, though, modules serve the role of libraries of tools, as we’ll learn in Part V. More generally, a module is mostly just a package of names, known as a namespace. And the names within that package are called attributes—variable names that are attached to a specific object.

In typical use, importers gain access to all the names assigned at the top level of a module’s file. These names are usually assigned to services exported by the module—functions, classes, variables, and so on—which are intended to be used in other files and other programs. Outside a file, its names can be fetched with two Python statements: import and from, as well as the reload call.

To illustrate, suppose we use a text editor to create the one-line Python module file myfile.py, shown in the following example. This may be one of the world’s simplest Python modules (it contains a single assignment statement), but it’s enough to illustrate the basics. When this file is imported, its code is run to generate the module’s attribute—this file’s assignment statement creates a module attribute named title:

title = "The Meaning of Life"

Now, we can access this module’s attribute title in other components two different ways. With the import statement, we get back the module as a whole, and qualify the module name by the attribute name to access:

% python                       
                   Start Python.
>>> import myfile               
                  Run file; load module as a whole.
>>> print myfile.title         
                   Use its attribute names: `.' to qualify.
The Meaning of Life

In general, the dot expression syntax object.attribute lets us fetch any attribute attached to any object, and is a common operation in Python code. Here, we use it to access the string variable title inside module myfile—that is, myfile.title. Alternatively, we can fetch (really, copy) names out of a module with from statements:

% python                        
                  Start Python.
>>> from myfile import title    
                  Run file; copy its names.
>>> print title                
                   Use name directly: no need to qualify.
The Meaning of Life

As we’ll see in more detail later, from is just like an import, with an extra assignment to names in the importing component. Because it also copies names from the imported file, though, we use imports directly without going through the original module name. Technically, from copies a module’s attributes, such that they become simple variables in the recipient—we simply refer to the imported string this time as title (a variable) instead of myfile.title (an attribute reference).[3]

Whether we use import or from to invoke an import operation, the statements in the module file myfile.py are executed, and the importing component (here, the interactive prompt) gains access to names assigned at the top level of the file. There’s only one such name in this simple example—the variable title, assigned to a string—but the concept will be more useful when we start defining more useful objects such as functions and classes in our modules. Such objects become reusable software components accessed by name from one or more client modules.

In practice, module files usually define more than one name to be used in and outside the file. Here’s an example that defines three:

a = 'dead'          # Define three attributes.
b = 'parrot'        # Exported to other files
c = 'sketch'
print a, b, c       # Also used in this file

This file, threenames.py, assigns three variables, and so generates three attributes for the outside world. It also uses its own three variables in a print statement, as we see when we run this as a top-level file:

% python threenames.py
dead parrot sketch

When this file is imported elsewhere, all its code runs as usual the first time it is imported (by either an import or from). Clients of this file that use import get a module with attributes; clients that use from get copies of the file’s names:

% python
>>> import threenames                  
                  Grab the whole module.
dead parrot sketch
>>>
>>> threenames.b, threenames.c
('parrot', 'sketch')
>>>
>>> from threenames import a, b, c     
                  Copy multiple names.
>>> b, c
('parrot', 'sketch')

The results here are printed in parenthesis, because they are really tuples—a kind of object covered in the next part of this book.

Once you start coding modules with multiple names like this, the built-in dir function starts to come in handy to fetch a list of the names available inside a module:

>>> dir(threenames)
['__builtins__', '__doc__', '__file__', '__name__', 'a', 'b', 'c']

When the dir function is called with the name of an imported module passed in parentheses like this, it returns all the attributes inside that module. Some of the names it returns are names you get “for free”: names with leading and trailing double underscores are built-in names that are always predefined by Python, and have special meaning to the interpreter. The variables our code defined by assignment—a, b, and c, show up last in the dir result.

Import and Reload Usage Notes

For some reason, once people find out about running by imports and reloads, many tend to focus on this alone, and forget about other launch options that always run the current version of the code (e.g., icon clicks, IDLE menu options, and command lines). This can lead to confusion quickly—you need to remember when you’ve imported to know if you can reload, need to remember to use parenthesis in reload (only), and need to remember to use reload in the first place to get the current version of your code to run.

Because of these complications (and others we’ll meet later), avoid the temptation to launch by imports and reloads for now. The IDLE Edit/RunScript menu option, for example, provides a simpler and less error-prone way to run your files. On the other hand, imports and reloads have proven to be a popular testing technique in Python classes, so you be the judge. If you find yourself running into a wall, though, stop.

There is more to the module story than exposed here, and you may run into trouble if you use modules in unusual ways at this point in the book; for instance, if you try to import a module file that is stored in a directory other than the one you’re working in, you’ll have to skip ahead to Chapter 15, and learn about the module search path. For now, if you must import, try to keep all your files in the directory you are working in, to avoid complications.

The IDLE User Interface

IDLE is a graphical user interface for doing Python development, and is a standard and free part of the Python system. It is usually referred to as an Integrated Development Environment (IDE), because it binds together various development tasks into a single view.[4]

In short, IDLE is a GUI that lets you edit, run, browse, and debug Python programs, all from a single interface. Moreover, because IDLE is a Python program that uses the Tkinter GUI toolkit, it runs portably on most Python platforms: MS Windows, X Windows (Unix, Linux), and Macs. For many, IDLE is an easy-to-use alternative to typing command lines, and a less problem-prone alternative to clicking on icons.

IDLE Basics

Let’s jump right into an example. IDLE is easy to start under Windows—it has an entry in the Start button menu for Python (see Figure 2-1); it can also be selected by right-clicking on a Python program icon. On some Unix-like systems, you may need to launch IDLE’s top-level script from a command line or icon click—start file idle.pyw in the idle subdirectory of Python’s Tools directory.[5]

Figure 3-3 shows the scene after starting IDLE on Windows. The Python Shell window at the bottom is the main window, which runs an interactive session (notice the >>> prompt). This works like all interactive sessions—code you type here is run immediately after you type it—and serves as a testing tool.

IDLE main window and text edit window
Figure 3-3. IDLE main window and text edit window

IDLE uses familiar menus with keyboard shortcuts for most of its operations. To make (or edit) a script under IDLE, open text edit windows—in the main window, select the File menu pulldown, and pick New window to open a text edit window (or Open... to edit an existing file). The window at the top of Figure 3-3 is an IDLE text edit window, where the code for file script3.py was entered.

Although this may not show up fully in this book, IDLE uses syntax-directed colorization for the code typed in both the main window, and all text edit windows—keywords are one color, literals are another, and so on. This helps give you a better picture of the components in your code.

To run a file of code that you are editing in IDLE, select the file’s text edit window, pick that window’s Edit menu pulldown, and choose the Run Script option there (or use the equivalent keyboard shortcut, listed in the menu). Python will let you know that you need to save your file first, if you’ve changed it since it was opened or last saved. (In Python 2.3, the menu structure changes slightly: the Run Module option in the new Run menu has the same effect as the prior version’s Edit/Runscript menu selection. See the sidebar IDLE Changes in 2.3 later in this chapter.)

When run this way, the output of your script, and any error messages it may generate, shows up back in the main interactive window. In Figure 3-3, for example, the last two lines in the bottom interactive window reflect an execution of the script in the top text edit window.

Tip

Hint of the day: To repeat prior commands in IDLE’s main interactive window, use Alt-P to scroll backwards through command history and Alt-N to scroll forwards. Your prior commands are recalled and displayed, and may be edited and rerun. You can also recall commands by positioning the cursor on them, or use cut-and-paste operations, but these tend to be more work. Outside IDLE, you may be able to recall commands in an interactive session with the arrow keys on Windows, if you’re running doskey or using a recent version of Windows.

Using IDLE

IDLE is free, easy to use, and portable. But it is also somewhat limited compared to more advanced commercial IDEs. Here are a list of common issues that seem to trip up IDLE beginners:

  • You must add “.py” explicitly when saving your files. We mentioned this when talking about files in general, but it’s a common IDLE stumbling block, especially for Windows users. IDLE does not automatically add a .py extension to file names when files are saved. Be careful to type the .py extension at the end of filenames yourself, when saving them for the first time. If you don’t, you will be able to run your file from IDLE (and command lines), but will not be able to import your file either interactively or from other modules.

  • Make sure you’re not looking at old error messages. IDLE currently does not do a good job of separating the output of each script execution in the interactive window—there is no blank line between the outputs. Because of that, many a beginner has been fooled by a prior run’s error message into thinking that their script is still failing, when in fact it is silently succeeding. Make sure the error messages you see are not old—typing an empty line in the interactive window helps.

  • Run scripts from text edit windows, not the interactive window. To run a file of code under IDLE, always select the Edit/RunScript menu option from within the text edit window where you are editing the code to be run—not from within the main interactive window where the >>> prompt appears. The RunScript option should arguably not be available in the interactive window at all (and in fact seems to have disappeared in the recent release); if you select it there, you’ll wind up trying to run a log of your interactive session, with less than desirable results!

  • Tkinter GUI programs may not work well with IDLE. Because IDLE is a Python/Tkinter program, it can be hung if you use it to run certain types of Python/Tkinter programs, especially if your code runs a Tkinter mainloop call. Your code may not exhibit such problems, but as a rule of thumb, it’s always safe if you use IDLE to edit GUI programs, but launch them using other options such as clicks or command lines.

  • Other programs may not work well with IDLE either. More generally, because IDLE currently (in 2.2) runs your code in the same process that IDLE itself runs in, it’s not impossible to hang IDLE with non-GUI programs as well. In fact, because IDLE uses neither processes nor threads to launch scripts, an infinite loop may render IDLE completely unresponsive. As a rule of thumb, if you can’t find a reason for a program failure under IDLE, try running the program outside IDLE to make sure your problem is not really an IDLE problem.

    This may improve over time (see the sidebar IDLE Changes in 2.3). The upside to this structure today is that, because your script is run in IDLE’s environment, variables in your code show up automatically in the IDLE interactive session—you don’t always need to run import commands to access names at the top level of files you’ve already run.

  • Run scripts by Edit/Run Script, not imports and reloads. In the prior section, we saw that it’s also possible to run a file by importing it interactively. However, this scheme can grow complex because you are required to manually reload files after changes. By contrast, the Edit/RunScript option in IDLE always runs the most current version of your file. It also prompts you to save it first, if needed—another common mistake outside IDLE.

    Technically speaking, IDLE’s Edit/Runscript option always runs the current version of the top-level file only; imported files may still need to be interactively reloaded when changed. In general, though, Edit/Runscript eliminates common confusions surrounding imports. If you choose to use the import and reload technique instead, remember to use Alt-P/Alt-N key combinations to recall prior commands.

  • Customizing IDLE. To change the text fonts and colors in IDLE, edit the configuration files in IDLE’s source directory. For example, for Python 2.2 on Windows, the file C:Python22Toolsidleconfig-win.txt specifies text font and size. See file config.txt in that directory or IDLE’s help pulldown menu for more hints. Also see the sidebar IDLE Changes in 2.3.

  • There is currently no clear-screen in IDLE. This seems to be a frequent request (perhaps because of similar IDEs), and might be added eventually. Today, though, there is no way to clear the interactive window’s text. If you want the window’s text to go away, you can press and hold the Enter key, or type a Python loop to print blank lines.

Besides the basic edit and run functions, IDLE provides more advanced features, including a point-and-click program debugger and an object browser. Figure 3-4, for example, shows the IDLE debugger and object browser windows in action. The browser allows you to navigate through the module search path to files and objects in files; clicking on a file or object opens the corresponding source in a text edit window.

IDLE debugger and path/object browser
Figure 3-4. IDLE debugger and path/object browser

IDLE debugging is initiated by selecting the Debug/Debugger menu option in the main window, and then starting your script by selecting the Edit/Run Script option in the text edit window; once started, you can set breakpoints in your code that stop its execution by right-clicking on lines in the text edit windows, show variable values, and so on. You can also watch program execution when debugging—selecting the debugger’s source toggle will cause the active line to be highlighted in the text edit window, as you step through your code.

In addition, IDLE’s text editor offers a large collection of programmer-friendly tools, including automatic indentation, advanced text and file search operations, and more. Because IDLE uses intuitive GUI interactions, experiment with the system live to get a feel for its other tools.

Other IDEs

Because IDLE is free, portable, and a standard part of Python, it’s a nice first development tool to become familiar with if you want to use an IDE at all. Use IDLE for this book’s exercises if you’re just starting out. There are, however, a handful of alternative IDEs for Python developers, some of which are substantially more powerful and robust than IDLE. Among the most commonly used today are these four:

Komodo

A full-featured development environment GUI for Python (and other languages). Komodo includes standard syntax-coloring text editing, debugging, and so on. In addition, Komodo offers many advanced features that IDLE does not, including project files, source-control integration, regular expression debugging, and a drag-and-drop GUI builder which generates Python/Tkinter code to implement the GUIs you design interactively. Komodo is not free as we write this; it is available at http://www.activestate.com.

PythonWorks

Another full-featured development environment GUI. PythonWorks also has standard IDE tools, and provides a Python/Tkinter GUI builder that generates Python code. In addition, it supports unique features such as automatic code refactoring, for optimal maintenance and reuse. This is also a commercial product; see http://www.pythonware.com for details.

PythonWin

A free IDE that ships as part of ActiveState’s ActivePython distribution (and may also be fetchable separately from http://www.python.org resources). PythonWin is a Windows-only IDE for Python; it is roughly like IDLE, with a handful of useful Windows-specific extensions added in. For instance, PythonWin has support for COM objects. It also adds basic user interface features beyond IDLE, such as object attribute list popups. Further, PythonWin serves as an example of using the Windows extension package’s GUI library. See http://www.activestate.com.

Visual Python

ActiveState also sells a system called Visual Python, which is a plug-in that adds Python support to Microsoft’s Visual Studio development environment. This is also a Windows-only solution, but is appealing to developers with a prior intellectual investment in Visual Studio. See ActiveState’s web site for details.

There are roughly half a dozen other well-known IDEs that we are aware of (e.g., WingIDE, PythonCard), and more will probably appear over time. Rather than trying to document them all here, see the resources available at http://www.python.org, as well as the Vaults of Parnassus web site.

Embedding Calls

So far, we’ve seen how to run code typed interactively, and how to launch code saved in files with command lines, icon clicks, IDEs, module imports, and Unix executable 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, parsed from an XML document, and so on. But from an operational perspective, another system—not you—may 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 C code snippet, a program coded in the C language 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, 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.[6] Regardless, you can still likely use the interactive and file-based launching techniques described here, to test code in isolation from those enclosing systems that may eventually use it.

Frozen Binary Executables

Frozen binary executables are packages that combine your program’s byte code and the Python interpreter into a single executable program. With these, programs can be launched in the same ways that you would launch any other executable program (icon clicks, command lines, etc.). While this option works well for delivery of products, it is not really intended for use during program development. You normally freeze just before shipping, and after development is finished.

Text Editor Launch Options

Many programmer-friendly text editors have support for editing, and possibly running, Python programs. Such support may be either built-in, or fetchable on the web. For instance, if you are familiar with the emacs text editor, you can do all your Python editing and launching from inside the text editor itself. See the text editor resources page at http://www.python.org/editors for more details.

Other Launch Options

Depending on your platform, there may be additional ways that you can start Python programs. For instance, on some Macintosh systems, you may be able to drag Python program file icons onto the Python interpreter icon, to make them execute. And on Windows, you can always start Python scripts with the Run... option in the Start menu. Finally, the Python standard library has utilities that allow Python programs to be started by other Python programs (e.g., execfile, os.popen, os.system); however, these tools are beyond the scope of the present chapter.

Future Possibilities?

Although this chapter reflects current practice, much of it has been both platform- and time-specific. Indeed, many of the execution and launch details presented arose between this book’s first and second editions. As for program execution, it’s not impossible that new program launch options may arise over time.

New operating systems, and new versions of them, may also provide execution techniques beyond those outlined here. In general, because Python keeps pace with such changes, you should be able to launch it in whatever way makes sense for the machines you use, both now and in the future—be that drawing on tablet PCs or PDAs, grabbing icons in a virtual reality, or shouting a script’s name over your coworkers’ conversations.

Implementation changes may also impact launch schemes somewhat (e.g., a full compiler could produce normal executables, launched much like frozen binaries today). If we knew what the future truly held, though, we would probably be talking to a stock broker instead of writing these words.

Which Option Should I Use?

With all these options, the question naturally arises: Which one is best for me? In general, use the IDLE interface for development, if you are just getting started with Python. It provides a user-friendly GUI environment, and can hide some of the underlying configuration details. It also comes with a platform-neutral text editor for coding your scripts, and is a standard and free part of the Python system.

If instead, you are an experienced programmer, you might be more comfortable with simply the text editor of your choice in one window, and another window for launching the programs you edit, by system command lines or icon clicks. Because development environments are a very subjective choice, we can’t offer much more in the way of universal guidelines; in general, the environment you like to use is usually the best to use.

Part I Exercises

It’s time to start doing a little coding on your own. This first exercise session is fairly simple, but a few of these questions hint at topics to come in later chapters. Remember, check Section B.1 for the answers; the exercises and their solutions sometimes contain supplemental information not discussed in the main part of the chapter. In other words, you should peek, even if you can manage to get all the answers on your own.

  1. Interaction. Using a system command line, IDLE, or other, start the Python interactive command line (>>> prompt), and type the expression: "Hello World!" (including the quotes). The string should be echoed back to you. The purpose of this exercise is to get your environment configured to run Python. In some scenarios, you may need to first run a cd shell command, type the full path to the python executable, or add its path to your PATH environment variable. If desired, you can set it in your .cshrc or .kshrc file to make Python permanently available on Unix systems; on Windows use a setup.bat, autoexec.bat, or the environment variable GUI. See Appendix A for help with environment variable settings.

  2. Programs. With the text editor of your choice, write a simple module file—a file containing the single statement: print 'Hello module world!‘. Store this statement in a file named module1.py. Now, run this file by using any launch option you like: running it in IDLE, clicking on its file icon, passing it to the Python interpreter program on the system shell’s command line, and so on. In fact, experiment by running your file with as many of the launch techniques seen in this chapter as you can. Which technique seems easiest? (There is no right answer to this one.)

  3. Modules. Next, start the Python interactive command line (>>> prompt) and import the module you wrote in Exercise 2. Try moving the file to a different directory and importing it again from its original directory (i.e., run Python in the original directory when you import); what happens? (Hint: is there still a file named module1.pyc in the original directory?)

  4. Scripts. If your platform supports it, add the #! line to the top of your module1.py module, give the file executable privileges, and run it directly as an executable. What does the first line need to contain? Skip that if you are working on a Windows machine (#! usually only has meaning on Unix and Linux); instead try running your file by listing just its name in a DOS console window (this works on recent versions of Windows), or the Start/Run... dialog box.

  5. Errors. Experiment with typing mathematical expressions and assignments at the Python interactive command line. First type the expression: 1 / 0; what happens? Next, type a variable name you haven’t assigned a value to yet; what happens this time?

    You may not know it yet, but you’re doing exception processing, a topic we’ll explore in depth in Part VII. As you’ll learn there, you are technically triggering what’s known as the default exception handler—logic that prints a standard error message.

    For full-blown source code debugging chores, IDLE includes a GUI debugging interface introduced in this chapter (see the advanced IDLE usage section), and a Python standard library module named pdb provides a command-line debugging interface (more on pdb in the standard library manual). When first starting out, Python’s default error messages will probably be as much error handling as you need—they give the cause of the error, as well as showing the lines in your code that were active when the error occurred.

  6. Breaks. At the Python command line, type:

    L = [1, 2]
    L.append(L)
    L

    What happens? If you’re using a Python newer than Release 1.5, you’ll probably see a strange output that we’ll describe in the next part of the book. If you’re using a Python version older than 1.5.1, a Ctrl-C key combination will probably help on most platforms. Why do you think this occurs? What does Python report when you type the Ctrl-C key combination? Warning: if you do have a Python older than Release 1.5.1, make sure your machine can stop a program with a break-key combination of some sort before running this test, or you may be waiting a long time.

  7. Documentation. Spend at least 17 minutes browsing the Python library and language manuals before moving on, to get a feel for the available tools in the standard library, and the structure of the documentation set. It takes at least this long to become familiar with the location of major topics in the manual set; once you do, it’s easy to find what you need. You can find this manual in the Python Start button entry on Windows, in the Help pulldown menu in IDLE, or online at http://www.python.org/doc. We’ll also have a few more words to say about the manuals and other documentation sources available (including PyDoc and the help function), in Chapter 11. If you still have time, go explore the Python web site (http://www.python.org), and the Vaults of Parnassus site link you’ll find there. Especially check out the python.org documentation and search pages; they can be crucial resources in practice.



[1] As seen when exploring command lines, modern Windows versions also let you type just the name of a .py file at the system command line—they use the registry to know to open the file with Python (e.g., typing brian.py is equivalent to typing python brian.py). This command-line mode is similar in spirit to the Unix #!. Note that some programs may actually interpret and use a first #! line on Windows much like Unix, but the DOS system shell and Windows itself ignores it completely.

[2] It is also possible to completely suppress the pop-up DOS console window for clicked files on Windows. Files whose names end in a .pyw extension will display only windows constructed by your script, not the default DOS console window. .pyw files are simply .py source files that have this special operational behavior on Windows. They are mostly used for Python-coded user interfaces that build windows of their own, and often in conjunction with various techniques for saving printed output and errors to files.

[3] Notice that import and from both list the name of the module file as simply myfile, without its .py suffix. As we’ll learn in Part V, when Python looks for the actual file, it knows to include the suffix in its search procedure. Again, remember to include the suffix in system shell command lines, but not in import statements.

[4] IDLE is a corruption of IDE, named in honor of Monty Python member Eric Idle.

[5] IDLE is a Python program that uses the standard library’s Tkinter GUI toolkit to build the IDLE GUI. This makes IDLE portable, but also means that you’ll need to have Tkinter support in your Python to use IDLE. The Windows version of Python does by default, but Linux and Unix users occasionally need to install the appropriate Tkinter support (see the installation hints in Appendix A for details).

[6] See Programming Python (O’Reilly) for more details on embedding Python in C/C++. The embedding API can call Python functions directly, load modules, and more. Also note that the Jython system allows Java programs to invoke Python code, using a Java-based API (a Python interpreter class).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset