




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































Dave Brueck and Stephen Tanner
REFERENCELANGUAGEPYTHONCOMPLETE INCLUDES A 100% O N E (^) H U N D R E D
(^) P E R C E N T
O N E (^) H U N D R E D
(^) P E R C E N T
Python 2.1 Bible
Python 2.1 Bible
Hungry Minds, Inc.
New York, NY ✦ Cleveland, OH ✦ Indianapolis, IN ✦
Python 2.1 Bible Published by Hungry Minds, Inc. 909 Third Avenue New York, NY 10022 www.hungryminds.com Copyright © 2001 Hungry Minds, Inc. All rights reserved. No part of this book, including interior design, cover design, and icons, may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording, or otherwise) without the prior written permission of the publisher. Library of Congress Catalog Card No.: 2001090703 ISBN: 0-7645-4807- Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 1B/RS/QW/QR/IN Distributed in the United States by Hungry Minds, Inc. Distributed by CDG Books Canada Inc. for Canada; by Transworld Publishers Limited in the United Kingdom; by IDG Norge Books for Norway; by IDG Sweden Books for Sweden; by IDG Books Australia Publishing Corporation Pty. Ltd. for Australia and New Zealand; by TransQuest Publishers Pte Ltd. for Singapore, Malaysia, Thailand, Indonesia, and Hong Kong; by Gotop Information Inc. for Taiwan; by ICG Muse, Inc. for Japan; by Intersoft for South Africa; by Eyrolles for France; by International Thomson Publishing for Germany, Austria, and Switzerland; by Distribuidora Cuspide for Argentina; by LR International for Brazil; by Galileo Libros for Chile; by Ediciones ZETA S.C.R. Ltda. for Peru; by WS Computer Publishing Corporation, Inc. for the Philippines; by Contemporanea de Ediciones for Venezuela; by Express Computer Distributors for the Caribbean and West Indies; by Micronesia Media Distributor, Inc. for Micronesia; by Chips Computadoras S.A. de C.V. for Mexico; by Editorial Norma de Panama S.A. for Panama; by American Bookshops for Finland.
For general information on Hungry Minds’ products and services please contact our Customer Care Department within the U.S. at 800-762-2974, outside the U.S. at 317-572-3993 or fax 317-572-4002. For sales inquiries and reseller information, including discounts, premium and bulk quantity sales, and foreign-language translations, please contact our Customer Care Department at 800-434-3422, fax 317-572-4002 or write to Hungry Minds, Inc., Attn: Customer Care Department, 10475 Crosspoint Boulevard, Indianapolis, IN 46256. For information on licensing foreign or domestic rights, please contact our Sub-Rights Customer Care Department at 212-884-5000. For information on using Hungry Minds’ products and services in the classroom or for ordering examination copies, please contact our Educational Sales Department at 800-434-2086 or fax 317-572-4005. For press review copies, author interviews, or other publicity information, please contact our Public Relations Department at 317-572-3168 or fax 317-572-4168. For authorization to photocopy items for corporate, personal, or educational use, please contact Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, or fax 978-750-4470.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND AUTHOR HAVE USED THEIR BEST EFFORTS IN PREPARING THIS BOOK. THE PUBLISHER AND AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS BOOK AND SPECIFICALLY DISCLAIM ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. THERE ARE NO WARRANTIES WHICH EXTEND BEYOND THE DESCRIPTIONS CONTAINED IN THIS PARAGRAPH. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES REPRESENTATIVES OR WRITTEN SALES MATERIALS. THE ACCURACY AND COMPLETENESS OF THE INFORMATION PROVIDED HEREIN AND THE OPINIONS STATED HEREIN ARE NOT GUARANTEED OR WARRANTED TO PRODUCE ANY PARTICULAR RESULTS, AND THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY INDIVIDUAL. NEITHER THE PUBLISHER NOR AUTHOR SHALL BE LIABLE FOR ANY LOSS OF PROFIT OR ANY OTHER COMMERCIAL DAMAGES, INCLUDING BUT NOT LIMITED TO SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR OTHER DAMAGES.
Trademarks: All trademarks are the property of their respective owners. Hungry Minds, Inc., is not associated with any product or vendor mentioned in this book.
is a trademark of Hungry Minds, Inc.
Credits
Acquisitions Editor Debra Williams Cauley
Project Editor Barbra Guerra
Technical Editor Joseph Traub
Copy Editors Lisa Blake Luann Rouff
Editorial Manager Colleen Totz
Project Coordinator Regina Snyder
Graphics and Production Specialists Brian Torwelle
Quality Control Technicians Laura Albert, Carl Pierce, Nancy Price, Charles Spencer
Book Designer Drew R. Moore
Proofreading and Indexing TECHBOOKS Production Services
About the Authors
Dave Brueck is a professional software developer who loves to use Python when- ever possible. His current projects include developing networked games, develop- ing Python interfaces to his stockbroker’s C SDK, and plotting to overturn various world governments. Previously Dave was a contributing author to 3D Studio Max R Bible by Kelly Murdock, published by Hungry Minds (formerly IDG Books Worldwide).
Stephen Tanner is currently using Python to build a black-box software testing frame- work. His side projects include Python tools to perform probabilistic derivatives- trading analysis, and to download mass quantities of .mp3s.
Aside from their “real” jobs, Dave and Stephen enjoy convincing people to pay them big bucks for consulting jobs.
To Jennie, Rachael, and Jacob — thanks for being patient. To Pokey the Penguin — NOW who is going to the restaurant? To the weeds in my unfinished back yard — playtime is over. — Dave
For great justice! — Stephen
Preface
P
ython is an object-oriented, interpreted programming language useful for a wide range of tasks, from small scripts to entire applications. It is freely avail- able in binary or source code form and can be used royalty-free on all major plat- forms including Windows, Macintosh, Linux, FreeBSD, and Solaris.
Compared with most programming languages, Python is very easy to learn and is considered by many to be the language of choice for beginning programmers. Instead of outgrowing the language, however, experienced developers enjoy lower maintenance costs without missing out on any features found in other major lan- guages such as C++, Java, or Perl.
Python is well known for its usefulness as a rapid application development tool, and we often hear of Python projects that finish in hours or days instead of the weeks or months that would have been required with traditional programming lan- guages. It boasts a rich, full-featured set of standard libraries as well as the ability to interface with libraries in other languages like C++.
Despite being incredibly powerful and enabling very rapid application develop- ment, the real reason we love to use Python is that it’s just plain fun. Python is like a lever — with it, you can do some pretty heavy lifting with very little effort. It frees you from lots of annoying, mundane work, and before long you begin to wonder how you endured your pre-Python days.
About This Book
Although Python is a great first programming language, in this book we do assume that you already have some programming experience.
The first section of the book introduces you to Python and tells you everything you need to know to get started. If you’re new to Python, then that section is definitely the place to start; otherwise, it serves as a useful language reference with many examples.
We’ve worked hard to ensure that the book works well as a quick reference. Often the quickest way to understand a feature is to see it in use: Flip through the book’s pages and you’ll see that they are dripping with code examples.
x Python 2.1 Bible
All the examples in the book work and are things you can try on your own. Where possible, the chapters also build complete applications that have useful and inter- esting purposes. We’ve gone to great lengths to explain not only how to use each module or feature but also why such a feature is useful.
What You Need
Besides the book, all you need is a properly installed copy of Python. Appendix A lists some Python resources available online, but a good place to start is www.python.org; it has prebuilt versions of Python for all major platforms as well as the Python source code itself. Once you’ve downloaded Python you’ll be under- way in a matter of minutes.
If you’re a user of Microsoft Windows, you can download an excellent distribution of Python from www.activestate.com. ActiveState provides a single download that includes Python, a free development environment and debugger, and Win extensions.
PythonWare (www.pythonware.com) also offers a distribution of Python that comes bundled with popular third-party Python modules. PythonWare’s version peacefully coexists with older versions of Python, and the small distribution size makes for a quick download.
No matter which site you choose, Python is free, so go download it and get started.
How the Book Is Organized
We’ve tried to organize the book so that related topics are close together. If you find the topic of one chapter particularly interesting, chances are that the chapters before and after it will pique your interest too.
Part I: The Python Language The first chapter in this section is a crash course in Python programming. If you have many programming languages under your belt or just want to whet your appetite, try out the examples in that chapter to get a feel for Python’s syntax and powerful features.
The remaining chapters in this first section cover the same material as Chapter 1 but in much greater detail. They work equally well as an initial tutorial of the Python language and as a language reference for seasoned Pythonistas.
xii Python 2.1 Bible
Appendixes Appendix A is a guide to online Python resources. Appendix B introduces you to IDLE and PythonWin — two great IDEs for developing Python programs. It also explains how to make Emacs handle Python code.
Conventions Used in This Book
Source code, function definitions, and interactive sessions appear in monospaced font. Comments appear in bold monospaced font preceded by a hash mark for easy reading. For example, this quick interpreter session checks the version of the Python interpreter. The >>> at the start of a line is the Python interpreter prompt and the text after the prompt is what you would type:
import sys # This is a comment. print sys.version 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)]
References to variables in function definitions appear in italics. For example, the function random.choice( seq ) chooses a random element from the sequence seq and returns it.
We divided up the writing of this book’s chapters between ourselves. So, through- out the book’s body, we use “I” (not “we”) to relate our individual opinions and experiences.
What the Icons Mean
Throughout the book, we’ve used icons in the left margin to call your attention to points that are particularly important.
This icon indicates that the material discussed is new to Python 2.0 or Python 2.1.
The Note icons tell you that something is important — perhaps a concept that may help you master the task at hand or something fundamental for understanding subsequent material.
Tip icons indicate a more efficient way of doing something or a technique that may not be obvious.
Tip
Note
New Feature
Preface xiii
Caution icons mean that the operation we’re describing can cause problems if you’re not careful.
We use the Cross-Reference icon to refer you to other sections or chapters that have more to say on a subject.
Visit Us!
We’ve set up a Web site for the book at www.pythonapocrypha.com. On the site you’ll find additional information, links to Python Web sites, and all the code sam- ples from the book (so you can be lazy and not type them in). The Web site also has a section where you can give feedback on the book, and we post answers to com- mon questions.
Have fun and enjoy the book!
Cross- Reference
Caution
Preface........................................... ix