BUY THIS BOOK
Add to Cart

Print Book $39.99


Add to Cart

Print+PDF $51.99

Add to Cart

PDF $31.99

Safari Books Online

What is this?

Add to UK Cart

Print Book £24.99

What is this?

Looking to Reprint or License this content?


Learning Python
Learning Python, Third Edition By Mark Lutz
October 2007
Pages: 746

Cover | Table of Contents | Colophon


Table of Contents

Chapter 1: A Python Q&A Session
If you've bought this book, you may already know what Python is, and why it's an important tool to learn. If you don't, you probably won't be sold on Python until you've learned the language by reading the rest of this book and have done a project or two. But before we jump into details, the first few pages of this book will briefly introduce some of the main reasons behind Python's popularity. To begin sculpting a definition of Python, this chapter takes the form of a question-and-answer session, which poses some of the most common questions asked by beginners.
Because there are many programming languages available today, this is the usual first question of newcomers. Given that there are roughly 1 million Python users out there at the moment, there really is no way to answer this question with complete accuracy. The choice of development tools is sometimes based on unique constraints or personal preference.
But after teaching Python to roughly 200 groups and 3,000 students during the last 10 years, some common themes have emerged. The primary factors cited by Python users seem to be these:
Software quality
For many, Python's focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence, reusable and maintainable—much more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented programming (OOP).
Developer productivity
Python boosts developer productivity many times beyond compiled or statically typed languages such as C, C++, and Java. Python code is typically one-third to one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps of some other tools, further boosting programmer speed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Why Do People Use Python?
Because there are many programming languages available today, this is the usual first question of newcomers. Given that there are roughly 1 million Python users out there at the moment, there really is no way to answer this question with complete accuracy. The choice of development tools is sometimes based on unique constraints or personal preference.
But after teaching Python to roughly 200 groups and 3,000 students during the last 10 years, some common themes have emerged. The primary factors cited by Python users seem to be these:
Software quality
For many, Python's focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence, reusable and maintainable—much more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented programming (OOP).
Developer productivity
Python boosts developer productivity many times beyond compiled or statically typed languages such as C, C++, and Java. Python code is typically one-third to one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps of some other tools, further boosting programmer speed.
Program portability
Most Python programs run unchanged on all major computer platforms. Porting Python code between Linux and Windows, for example, is usually just a matter of copying a script's code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program launches and directory processing, are as portable in Python as they can possibly be.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Is Python a "Scripting Language"?
Python is a general-purpose programming language that is often applied in scripting roles. It is commonly defined as an object-oriented scripting language—a definition that blends support for OOP with an overall orientation toward scripting roles. In fact, people often use the word "script" instead of "program" to describe a Python code file. In this book, the terms "script" and "program" are used interchangeably, with a slight preference for "script" to describe a simpler top-level file, and "program" to refer to a more sophisticated multifile application.
Because the term "scripting language" has so many different meanings to different observers, some would prefer that it not be applied to Python at all. In fact, people tend to make three very different associations, some of which are more useful than others, when they hear Python labeled as such:
Shell tools
Sometimes when people hear Python described as a scripting language, they think it means that Python is a tool for coding operating-system-oriented scripts. Such programs are often launched from console command lines, and perform tasks such as processing text files and launching other programs.
Python programs can and do serve such roles, but this is just one of dozens of common Python application domains. It is not just a better shell-script language.
Control language
To others, scripting refers to a "glue" layer used to control and direct (i.e., script) other application components. Python programs are indeed often deployed in the context of larger applications. For instance, to test hardware devices, Python programs may call out to components that give low-level access to a device. Similarly, programs may run bits of Python code at strategic points to support end-user product customization without having to ship and recompile the entire system's source code.
Python's simplicity makes it a naturally flexible control tool. Technically, though, this is also just a common Python role; many Python programmers code standalone scripts without ever using or knowing about any integrated components. It is not just a control language.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
OK, but What's the Downside?
After using Python for 15 years and teaching it for 10, the only downside to Python I've found is that, as currently implemented, its execution speed may not always be as fast as compiled languages such as C and C++.
We'll talk about implementation concepts in detail later in this book. In short, the standard implementations of Python today compile (i.e., translate) source code statements to an intermediate format known as byte code, and then interpret the byte code. Byte code provides portability, as it is a platform-independent format. However, because Python is not compiled all the way down to binary machine code (e.g., instructions for an Intel chip), some programs will run more slowly in Python than in a fully compiled language like C.
Whether you will ever care about the execution speed difference depends on what kinds of programs you write. Python has been optimized numerous times, and Python code runs fast enough by itself in most application domains. Furthermore, whenever you do something "real" in a Python script, like process a file or construct a GUI, your program is actually running at C speed, since such tasks are immediately dispatched to compiled C code inside the Python interpreter. More fundamentally, Python's speed-of-development gain is often far more important than any speed-of-execution loss, especially given modern computer speeds.
Even at today's CPU speeds, though, there still are some domains that do require optimal execution speeds. Numeric programming and animation, for example, often need at least their core number-crunching components to run at C speed (or better). If you work in such a domain, you can still use Python—simply split off the parts of the application that require optimal speed into compiled extensions, and link those into your system for use in Python scripts.
We won't talk about extensions much in this text, but this is really just an instance of the Python-as-control-language role that we discussed earlier. A prime example of this dual language strategy is the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Who Uses Python Today?
At this writing, in 2007, the best estimate anyone can seem to make of the size of the Python user base is that there are roughly 1 million Python users around the world today (plus or minus a few). This estimate is based on various statistics, like download rates and developer surveys. Because Python is open source, a more exact count is difficult—there are no license registrations to tally. Moreover, Python is automatically included with Linux distributions, Macintosh computers, and some products and hardware, further clouding the user-base picture.
In general, though, Python enjoys a large user base, and a very active developer community. Because Python has been around for more than 15 years and has been widely used, it is also very stable and robust. Besides being employed by individual users, Python is also being applied in real revenue-generating products by real companies. For instance:
  • Google makes extensive use of Python in its web search system, and employs Python's creator.
  • The YouTube video sharing service is largely written in Python.
  • The popular BitTorrent peer-to-peer file sharing system is a Python program.
  • Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.
  • Industrial Light & Magic, Pixar, and others use Python in the production of movie animation.
  • JPMorgan Chase, UBS, Getco, and Citadel apply Python for financial market forecasting.
  • NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming tasks.
  • iRobot uses Python to develop commercial robotic vacuum cleaners.
  • ESRI uses Python as an end-user customization tool for its popular GIS mapping products.
  • The NSA uses Python for cryptography and intelligence analysis.
  • The IronPort email server product uses more than 1 million lines of Python code to do its job.
  • The One Laptop Per Child (OLPC) project builds its user interface and activity model in Python.
And so on. Probably the only common thread amongst the companies using Python today is that Python is used all over the map, in terms of application domains. Its general-purpose nature makes it applicable to almost all fields, not just one. In fact, it's safe to say that Python is being used by virtually every substantial organization writing software, whether for short-term tactical tasks such as testing and administration, or for long-term strategic product development. Python has proven to work well in both modes.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Can I Do with Python?
Besides being a well-designed programming language, Python is also useful for accomplishing real-world tasks—the sorts of things developers do day in and day out. It's commonly used in a variety of domains, as a tool for scripting other components and implementing standalone programs. In fact, as a general-purpose language, Python's roles are virtually unlimited: you can use it for everything from web site development and gaming, to robotics and spacecraft control.
However, the most common Python roles currently seem to fall into a few broad categories. The next few sections describe some of Python's most common applications today, as well as tools used in each domain. We won't be able to explore the tools mentioned here in any depth—if you are interested in any of these topics, see the Python web site, or other resources for more details.
Python's built-in interfaces to operating-system services make it ideal for writing portable, maintainable system-administration tools and utilities (sometimes called shell tools). Python programs can search files and directory trees, launch other programs, do parallel processing with processes and threads, and so on.
Python's standard library comes with POSIX bindings and support for all the usual OS tools: environment variables, files, sockets, pipes, processes, multiple threads, regular expression pattern matching, command-line arguments, standard stream interfaces, shell-command launchers, filename expansion, and more. In addition, the bulk of Python's system interfaces are designed to be portable; for example, a script that copies directory trees typically runs unchanged on all major Python platforms.
Python's simplicity and rapid turnaround also make it a good match for graphical user interface (GUI) programming. Python comes with a standard object-oriented interface to the Tk GUI API called Tkinter, which allows Python programs to implement portable GUIs with a native look and feel. Python/Tkinter GUIs run unchanged on MS Windows, X Windows (on Unix and Linux), and the Mac OS (both Classic and OS X). A free extension package,
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
What Are Python's Technical Strengths?
Naturally, this is a developer's question. If you don't already have a programming background, the language in the next few sections may be a bit baffling—don't worry, we'll explore all of these terms in more detail as we proceed through this book. For developers, though, here is a quick introduction to some of Python's top technical features.
Python is an object-oriented language, from the ground up. Its class model supports advanced notions such as polymorphism, operator overloading, and multiple inheritance; yet, in the context of Python's simple syntax and typing, OOP is remarkably easy to apply. In fact, if you don't understand these terms, you'll find they are much easier to learn with Python than with just about any other OOP language available.
Besides serving as a powerful code structuring and reuse device, Python's OOP nature makes it ideal as a scripting tool for object-oriented systems languages such as C++ and Java. For example, with the appropriate glue code, Python programs can subclass (specialize) classes implemented in C++, Java, and C#.
Of equal significance, OOP is an option in Python; you can go far without having to become an object guru all at once. Much like C++, Python supports both procedural and object-oriented programming modes. Its object-oriented tools can be applied if and when constraints allow. This is especially useful in tactical development modes, which preclude design phases.
Python is completely free to use and distribute. As with other open source software, such as Tcl, Perl, Linux, and Apache, you can fetch the entire Python system's source code for free on the Internet. There are no restrictions on copying it, embedding it in your systems, or shipping it with your products. In fact, you can even sell Python's source code, if you are so inclined.
But don't get the wrong idea: "free" doesn't mean "unsupported." On the contrary, the Python online community responds to user queries with a speed that most commercial software vendors would do well to notice. Moreover, because Python comes with complete source code, it empowers developers, leading to the creation of a large team of implementation experts. Although studying or changing a programming language's implementation isn't everyone's idea of fun, it's comforting to know that it's available as a final resort and ultimate documentation source. You're not dependent on the whims of a commercial vendor.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
How Does Python Stack Up to Language X?
Finally, to place it in the context of what you may already know, people sometimes compare Python to languages such as Perl, Tcl, and Java. We talked about performance earlier, so here we'll focus on functionality. While other languages are also useful tools to know and use, many people find that Python:
  • Is more powerful than Tcl. Python's support for "programming in the large" makes it applicable to the development of larger systems.
  • Has a cleaner syntax and simpler design than Perl, which makes it more readable and maintainable, and helps reduce program bugs.
  • Is simpler and easier to use than Java. Python is a scripting language, but Java inherits much of the complexity and syntax of systems languages such as C++.
  • Is simpler and easier to use than C++, but often doesn't compete with C++, either; as a scripting language, Python often serves different roles.
  • Is both more powerful and more cross-platform than Visual Basic. Its open source nature also means it is not controlled by a single company.
  • Is more mature and has a more readable syntax than Ruby. Unlike Ruby and Java, OOP is an option in Python—Python does not impose OOP on users or projects to which it may not apply.
  • Has the dynamic flavor of languages like SmallTalk and Lisp, but also has a simple, traditional syntax accessible to developers as well as end users of customizable systems.
Especially for programs that do more than scan text files, and that might have to be read in the future by others (or by you!), many people find that Python fits the bill better than any other scripting or programming language available today. Furthermore, unless your application requires peak performance, Python is often a viable alternative to systems development languages such as C, C++, and Java: Python code will be much less difficult to write, debug, and maintain.
Of course, your author has been a card-carrying Python evangelist since 1992, so take these comments as you may. They do, however, reflect the common experience of many developers who have taken time to explore what Python has to offer.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter Summary
And that concludes the hype portion of this book. In this chapter, we've explored some of the reasons that people pick Python for their programming tasks. We've also seen how it is applied, and a representative sample of who is using it today. My goal is to teach Python, though, not to sell it. The best way to judge a language is to see it in action, so the rest of this book focuses entirely on the language details we've glossed over here.
To get started, the next two chapters begin our technical introduction to the language. There, we explore ways to run Python programs, peek at Python's byte code execution model, and introduce the basics of module files for saving code. The goal will be to give you just enough information to run the examples and exercises in the rest of the book. You won't really start programming until , but make sure you have a handle on the startup details before moving on.
Chapter Quiz
In this edition of the book, we will be closing each chapter with a quick pop quiz about the material presented to help you review the key concepts. The answers for these quizzes appear immediately after the questions, and you are encouraged to read the answers once you've taken a crack at the questions yourself. In addition to these end-of-chapter quizzes, you'll find lab exercises at the end of each part of the book, designed to help you start coding Python on your own. For now, here's your first test. Good luck!
Q:
What are the six main reasons that people choose to use Python?
Q:
Name four notable companies or organizations using Python today.
Q:
Why might you not want to use Python in an application?
Q:
What can you do with Python?
Q:
What's the significance of the Python import this statement?
Q:
Why does "spam" show up in so many Python examples in books and on the Web?
Q:
What is your favorite color?
Quiz Answers
How did you do? Here are the answers I came up with, though there may be multiple solutions to some quiz questions. Again, even if you're sure you got a question right, I encourage you to look at these answers for additional context. See the chapter's text for more details if any of these responses don't make sense to you.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: How Python Runs Programs
This chapter and the next give a quick look at program execution—how you launch code, and how Python runs it. In this chapter, we'll study the Python interpreter. will then show you how to get your own programs up and running.
Startup details are inherently platform-specific, and some of the material in this chapter may not apply to the platform you work on, so you should feel free to skip parts not relevant to your intended use. Likewise, more advanced readers who have used similar tools in the past and prefer to get to the meat of the language quickly may want to file some of this chapter away as "for future reference." For the rest of you, let's learn how to run some code.
So far, I've mostly been talking about Python as a programming language. But, as currently implemented, it's also a software package called an interpreter. An interpreter is a kind of program that executes other programs. When you write a Python program, the Python interpreter reads your program and carries out the instructions it contains. In effect, the interpreter is a layer of software logic between your code and the computer hardware on your machine.
When the Python package is installed on your machine, it generates a number of components—minimally, an interpreter and a support library. 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. Depending on which flavor of Python you run, the interpreter itself may be implemented as a C program, a set of Java classes, or something else. Whatever form it takes, the Python code you write must always be run by this interpreter. And, to enable that, you must install a Python interpreter on your computer.
Python installation details vary by platform, and are covered in more depth in . In short:
  • Windows users fetch and run a self-installing executable file that puts Python on their machines. Simply double-click and say Yes or Next at all prompts.
  • On Windows Vista, you may need to take extra steps to use the Python 2.5 MSI installer file; see for more details.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introducing the Python Interpreter
So far, I've mostly been talking about Python as a programming language. But, as currently implemented, it's also a software package called an interpreter. An interpreter is a kind of program that executes other programs. When you write a Python program, the Python interpreter reads your program and carries out the instructions it contains. In effect, the interpreter is a layer of software logic between your code and the computer hardware on your machine.
When the Python package is installed on your machine, it generates a number of components—minimally, an interpreter and a support library. 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. Depending on which flavor of Python you run, the interpreter itself may be implemented as a C program, a set of Java classes, or something else. Whatever form it takes, the Python code you write must always be run by this interpreter. And, to enable that, you must install a Python interpreter on your computer.
Python installation details vary by platform, and are covered in more depth in . In short:
  • Windows users fetch and run a self-installing executable file that puts Python on their machines. Simply double-click and say Yes or Next at all prompts.
  • On Windows Vista, you may need to take extra steps to use the Python 2.5 MSI installer file; see for more details.
  • Linux and Mac OS X users probably already have a usable Python preinstalled on their computers—it's a standard component on these platforms today.
  • Some Linux users (and most Unix users) typically either install Python from RPM files, or compile it from its full source code distribution package.
  • Other platforms have installation techniques relevant to those platforms. For instance, Python is also available on cell phones, game consoles, and iPods, but the installation details vary too widely to cover here.
Python itself may be fetched from the downloads page at Python's web site. It may also be found through various other distribution channels. Keep in mind that you should always check to see whether Python is already present before installing it. If you're working on Windows, you'll usually find Python in the Start menu, as captured in (these menu options are discussed in the next chapter). On Unix and Linux, Python probably lives in your
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Program Execution
What it means to write and run a Python script depends on whether you look at these tasks as a programmer, or as a Python interpreter. Both views offer important perspectives on Python programming.
In its simplest form, a Python program is just a text file containing Python statements. For example, the following file, named script1.py, is one of the simplest Python scripts we could dream up, but it passes for an official Python program:

print 'hello world'
print 2 ** 100
This file contains two Python print statements, which simply print a string (the text in quotes) and a numeric expression result (2 to the power 100) to the output stream. Don't worry about the syntax of this code yet—for this chapter, we're interested only in getting it to run. I'll explain the print statement, and why you can raise 2 to the power 100 in Python without overflowing, in later parts of this book.
You can create such a file of statements with any text editor you like. By convention, Python program files are given names that end in .py; technically, this naming scheme is required only for files that are "imported," as shown later in this book, but most Python files have .py names for consistency.
After you've typed these statements into a text file, you must tell Python to execute the file—which simply means to run all the statements in the file from top to bottom, one after another. As you'll see in the next chapter, you can launch Python program files by command lines, by clicking their icons, and with other standard techniques. If all goes well, when you execute the file, you'll see the results of the two print statements show up somewhere on your computer—by default, usually in the same window you were in when you ran the program:

hello world
1267650600228229401496703205376km
For example, here's what happened when I ran this script from a DOS command line on a Windows laptop (typically called a Command Prompt window, found in the Accessories program menu), to make sure it didn't have any silly typos:

D:\temp> python script1.py
hello world
1267650600228229401496703205376
We've just run a Python script that prints a string and a number. We probably won't win any programming awards with this code, but it's enough to capture the basics of program execution.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Execution Model Variations
Before moving on, I should point out that the internal execution flow described in the prior section reflects the standard implementation of Python today, and is not really a requirement of the Python language itself. Because of that, the execution model is prone to changing with time. In fact, there are already a few systems that modify the picture in somewhat. Let's take a few moments to explore the most prominent of these variations.
Really, as this book is being written, there are three primary implementations of the Python language—CPython, Jython, and IronPython—along with a handful of secondary implementations such as Stackless Python. In brief, CPython is the standard implementation; all the others have very specific purposes and roles. All implement the same Python language, but execute programs in different ways.

CPython

The original, and standard, implementation of Python is usually called CPython, when you want to contrast it with the other two. Its name comes from the fact that it is coded in portable ANSI C language code. This is the Python that you fetch from http://www.python.org, get with the ActivePython distribution, and have automatically on most Linux and Mac OS X machines. If you've found a preinstalled version of Python on your machine, it's probably CPython, unless your company is using Python in very specialized ways.
Unless you want to script Java or .NET applications with Python, you probably want to use the standard CPython system. Because it is the reference implementation of the language, it tends to run the fastest, be the most complete, and be more robust than the alternative systems. reflects CPython's runtime architecture.

Jython

The Jython system (originally known as JPython) is an alternative implementation of the Python language, targeted for integration with the Java programming language. Jython consists of Java classes that compile Python source code to Java byte code and then route the resulting byte code to the Java Virtual Machine (JVM). Programmers still code Python statements in .py text files as usual; the Jython system essentially just replaces the rightmost two bubbles in with Java-based equivalents.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter Summary
This chapter introduced the execution model of Python (how Python runs your programs) and explored some common variations on that model (just-in-time compilers and the like). Although you don't really need to come to grips with Python internals to write Python scripts, a passing acquaintance with this chapter's topics will help you truly understand how your programs run once you start coding them. In the next chapter, you'll start actually running some code of your own. First, though, here's the usual chapter quiz.
Chapter Quiz
Q:
What is the Python interpreter?
Q:
What is source code?
Q:
What is byte code?
Q:
What is the PVM?
Q:
Name two variations on Python's standard execution model.
Q:
How are CPython, Jython, and IronPython different?
Quiz Answers
Q:A:
The Python interpreter is a program that runs the Python programs you write.
Q:A:
Source code is the statements you write for your program—it consists of text in text files that normally end with a .py extension.
Q:A:
Byte code is the lower-level form of your program after Python compiles it. Python automatically stores byte code in files with a .pyc extension.
Q:A:
The PVM is the Python Virtual Machine—the runtime engine of Python that interprets your compiled code.
Q:A:
Psyco, Shedskin, and frozen binaries are all variations on the execution model.
Q:A:
CPython is the standard implementation of the language. Jython and IronPython implement Python programs for use in Java and .NET environments, respectively; they are alternative compilers for Python.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 3: How You Run Programs
OK, 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, I'll assume that you have Python installed on your computer; if not, see the prior chapter and 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 how to type code interactively, and how to save it in files to be run with system command lines, icon clicks, module imports, IDE GUIs such as IDLE and Eclipse, and more.
If you just want to find out how to run a Python program quickly, you may be tempted to read the parts that pertain only to your platform and move on to . But don't skip the material on module imports, as that's essential to understanding Python's program architecture. I also encourage you at least to skim the sections on IDLE and other IDEs, so you'll know what tools are available for when you start developing more sophisticated Python programs.
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 just to type python at your operating system's prompt, without any arguments. For example:

% python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Typing the word "python" at your system shell prompt begins an interactive Python session (the "%" character stands for your system's prompt, not input that you type yourself). The notion of a system shell prompt is generic, but exactly how you access the prompt varies by platform:
  • On Windows, you can type python in a DOS console window (a.k.a. the Command Prompt, usually found in the Accessories section of the Programs menu of your Start button) or in the Start → Run . . . dialog box.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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 just to type python at your operating system's prompt, without any arguments. For example:

% python
Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Typing the word "python" at your system shell prompt begins an interactive Python session (the "%" character stands for your system's prompt, not input that you type yourself). The notion of a system shell prompt is generic, but exactly how you access the prompt varies by platform:
  • On Windows, you can type python in a DOS console window (a.k.a. the Command Prompt, usually found in the Accessories section of the Programs menu of your Start button) or in the Start → Run . . . dialog box.
  • On Unix, Linux, and Mac OS X, you might type this command in a shell or terminal 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.
If you have not set your shell's PATH environment variable to include Python's install directory, you may need to replace the word "python" with the full path to the Python executable on your machine. On Windows, try typing C:\Python25\python (for version 2.5); on Unix and Linux, /usr/local/bin/python (or /usr/bin/python) will often suffice. Alternatively, you can run a change-directory command to go to Python's install directory before typing "python" (try a cd c:\python25 command on Windows, for instance).
The Python interactive session begins by printing two lines of informational text (which I'll omit from this book's examples to save space), then prompts for input with
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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, which are 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. Regardless of how it is run, Python executes all the code in a module file from top to bottom each time you run the file.
Terminology in this domain can vary somewhat. For instance, module files are often referred to as programs in Python—that is, a program is considered to be a series of precoded statements stored in a file for repeated execution. Module files that are run directly are also sometimes called scripts—an informal term meaning a top-level program file. Some reserve the term "module" for a file imported from another file. (More on the meaning of "top-level" and imports in a few moments.)
Whatever you call them, the next few sections explore ways to run code typed into module files. In this section, you'll learn how to 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, start your favorite text editor (e.g., vi, Notepad, or the IDLE editor), and type two 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 some Python
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Clicking File Icons
On Windows, the Registry makes opening files with icon clicks easy. 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 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 discussed in 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.
To illustrate, suppose you create the following program file with your text editor and save it as 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 you must import to load). You can run this file from a system command line:

D:\LP3E\Examples> c:\python25\python script4.py
win32
1267650600228229401496703205376
However, icon clicks allow you to run the file without any typing at all. If you find this file's icon—for instance, by selecting My Computer and working your way down on the D drive—you will get the file explorer picture captured in (Windows XP is being used here). In Python 2.5, source files show up with white backgrounds on Windows, and byte code files show up with black backgrounds. 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.
Figure : On Windows, Python program files show up as icons in file explorer windows, and can automatically be run with a double-click of the mouse (though you might not see printed output or error messages this way).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Module Imports and Reloads
So far, I've been talking about "importing modules" without really explaining what this term means. We'll study modules and larger program architecture in depth in , but because imports are also a way to launch programs, this section will introduce enough module basics to get you started.
In simple terms, every file of Python source code whose name ends in a .py extension is a module. Other files can access the items a module defines by importing that module; import operations essentially load another file, and grant access to that file's contents. The contents of a module are made available to the outside world through its attributes (a term I'll define in the next section).
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 architectural 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 you start an interactive session (in IDLE, from a command line, or otherwise), you can run the script4.py file you created earlier with a simple import:

D:\LP3E\Examples> c:\python25\python
>>> 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 you 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 you'll learn in , imports must find files, compile to byte code, and run the code.
If you really want to force Python to run the file again in the same session (without stopping and restarting the session), you need to instead call the built-in
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
The IDLE User Interface
So far, we've seen how to run Python code with the interactive prompt, system command lines, icon clicks, and module imports. If you're looking for something a bit more visual, IDLE provides a graphical user interface (GUI) for doing Python development, and it's 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.
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, including Microsoft Windows, X Windows (for Linux, Unix, and Unix-like platforms), and the Mac OS (both Classic and OS X). For many, IDLE represents an easy-to-use alternative to typing command lines, and a less problem-prone alternative to clicking on icons.
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 ), and 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, alternatively, by clicking on the icon for the idle.pyw or idle.py file located in the idlelib subdirectory of Python's Lib directory. (On Windows, IDLE is a Python script that currently lives in C:\Python25\Lib\idlelib.)
shows the scene after starting IDLE on Windows. The Python shell window that opens initially 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.
Figure : The main Python shell window of the IDLE development GUI, shown here running on Windows. Use the File menu to begin (New Window), or change (Open ... ) a source file; use the file edit window's Run menu to run the code in that window (Run Module).
IDLE uses familiar menus with keyboard shortcuts for most of its operations. To make (or edit) a source code file under IDLE, open a text edit window: in the main window, select the File pull-down menu, and pick New Window to open a text edit window (or Open . . . to edit an existing file). A new window will appear. This is an IDLE text edit window, where the code for the file you are creating or changing is entered and displayed.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
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. Again, I recommend that you use IDLE for this book's exercises if you're just starting out, unless you are already familiar with a command-line-based development mode. There are, however, a handful of alternative IDEs for Python developers, some of which are substantially more powerful and robust than IDLE. Here are some of the most commonly used IDEs:
Eclipse and PyDev
Eclipse is an advanced open source IDE GUI. Originally developed as a Java IDE, Eclipse also supports Python development when you install the PyDev (or similar) plug-in. Eclipse is a popular and powerful option for Python development, and it goes well beyond IDLE's feature set. Its downsides seem to be that it is a large system to install, and its PyDev plug-in requires a shareware extensions package for some features (including an integrated interactive console) that is not strictly open source. Still, when you are ready to graduate from IDLE, the Eclipse/PyDev combination is worth your attention.
Komodo
A full-featured development environment GUI for Python (and other languages), Komodo includes standard syntax-coloring, text-editing, debugging, and other features. 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 that generates Python/Tkinter code to implement the GUIs you design interactively. At this writing, Komodo is not free; it is available at http://www.activestate.com.
PythonWin
PythonWin is a free Windows-only IDE for Python that ships as part of ActiveState's ActivePython distribution (and may also be fetched separately from http://www.python.org resources). It is roughly like IDLE, with a handful of useful Windows-specific extensions added; for example, PythonWin has support for COM objects. Today, IDLE is probably more advanced than PythonWin (for instance, IDLE's dual-process architecture more often prevents it from becoming hung). However, PythonWin still offers tools for Windows developers that IDLE does not. See
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Embedding Calls
At this point, we've seen how to run code typed interactively, and how to launch code saved in files with system command lines, Unix executable scripts, icon clicks, module imports, and IDEs like IDLE. That covers most of the cases you'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 the 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. Such an embedded execution mode is commonly used to support end user customization—a game program, for instance, might allow for play modifications by running user-accessible embedded Python code at strategic points in time.
As an 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. 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.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Frozen Binary Executables
Frozen binary executables, described in the preceding chapter, are packages that combine your program's byte code and the Python interpreter into a single executable program. With these, Python 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 (after development is finished). See the prior chapter for more on this option.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Text Editor Launch Options
As mentioned previously, although not full-blown IDE GUIs, most programmer-friendly text editors have