Docsity

Biblia do python com exemplos para consulta, Manuais, Projetos, Pesquisas de Programação em Python

Toggle sidebar
bg1
BRUECK
TANNER
If Python 2.1 can do it, you can do it too . . .
Packed with crystal-clear explanations, hands-on examples, and a complete language reference, this
authoritative guide gives you all the tools you need for rapid application development with Python 2.1.
From variables, expressions, and other basics to XML, multimedia, and multithreading, Python pros
Dave Brueck and Stephen Tanner show you step by step how to master Python components, put them
together, and create full-featured applications — in practically no time!
Inside, you’ll find complete
coverage of Python 2.1
•Get up to speed on basics with a quick one-hour tutorial
•Work with Python data types, expressions, and object-
oriented features
•Take advantage of Python operating system services
and database features
•Create Web-savvy applications that can handle
Internet data and parse XML
•Build graphical applications using Tkinter and wxPython
•Process sound and image files
•Harness multithreading, encryption, tokenizing, and other
advanced techniques
•Use Python tools to create number-crunching routines
and internationalized applications
•Distribute Python applications and modules on a
Windows or UNIX system
Shelving Category:
Programming
Reader Level:
Beginning to Advanced
ISBN 0-7645-4807-7
$39.99 USA
$59.99 Canada
£29.99 UK
Python 2.1
Python 2.1
Master all major
Python components
and see how they
work together
Leverage Python
standard libraries
for rapid application
development
Harness XML,
Unicode, and other
cutting-edge
technologies
Python 2.1
Dave Brueck and Stephen Tanner
,!7IA7G4-feiahj!:p;N;t;T;t
Includes a complete
language reference INCLUDES A
COMPLETE
PYTHON
LANGUAGE
REFERENCE
www.hungryminds.com
100%
ONE HUNDRED PERCENT
COMPREHENSIVE
AUTHORITATIVE
WHAT YOU NEED
ONE HUNDRED PERCENT
Use
scales and
listboxes
to design
a color
scheme
Python 2.1
*85555-AHCEJh
100%
COMPREHENSIVE
Bible
See the
chat/whiteboard
application
in action
Use the
device
contexts
to draw
graphics
4807-7 cover 5/16/01 12:25 PM Page 1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe Biblia do python com exemplos para consulta e outras Manuais, Projetos, Pesquisas em PDF para Programação em Python, somente na Docsity!

Master

all major

Leveragework togetherand see how theyPython components

Python

Harnessdevelopmentfor rapid applicationstandard libraries

XML,

technologiescutting-edgeUnicode, and other

P

ython 2.

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

W H A T Y O UA U T H O R I T A T I V E C O M P R E H E N S I V E

N E E D

O N E (^) H U N D R E D

(^) P E R C E N T

P

ython 2.

Python 2.1 Bible

Python 2.1 Bible

Dave Brueck and Stephen Tanner

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

Contents at a Glance

Preface........................................... ix

  • Part I: The Python Language Acknowledgments xiv
  • Chapter 1: Python in an Hour
  • Chapter 2: Identifiers, Variables, and Numeric Types
  • Chapter 3: Expressions and Strings
  • Chapter 4: Advanced Data Types
  • Chapter 5: Control Flow
  • Chapter 6: Program Organization
  • Chapter 7: Object-Oriented Python
  • Chapter 8: Input and Output
  • Part II: Files, Data Storage, and Operating System Services
  • Chapter 9: Processing Strings and Regular Expressions
  • Chapter 10: Working with Files and Directories
  • Chapter 11: Using Other Operating System Services
  • Chapter 12: Storing Data and Objects
  • Chapter 13: Accessing Date and Time
  • Chapter 14: Using Databases
  • Part III: Networking and the Internet
  • Chapter 15: Networking
  • Chapter 16: Speaking Internet Protocols
  • Chapter 17: Handling Internet Data
  • Chapter 18: Parsing XML and Other Markup Languages
  • Part IV: User Interfaces and Multimedia
  • Chapter 19: Tinkering with Tkinter
  • Chapter 20: Using Advanced Tkinter Widgets
  • Chapter 21: Building User Interfaces with wxPython
  • Chapter 22: Using Curses
  • Chapter 23: Building Simple Command Interpreters
  • Chapter 24: Playing Sound
  • Part V: Advanced Python Programming
  • Chapter 25: Processing Images
  • Chapter 26: Multithreading
  • Chapter 27: Debugging, Profiling, and Optimization
  • Chapter 28: Security and Encryption
  • Chapter 29: Writing Extension Modules
  • Chapter 30: Embedding the Python Interpreter
  • Chapter 31: Number Crunching
  • Chapter 32: Using NumPy
  • Chapter 33: Parsing and Interpreting Python Code
  • Part VI: Deploying Python Applications
  • Chapter 34: Creating Worldwide Applications
  • Chapter 35: Customizing Import Behavior
  • Chapter 36: Distributing Modules and Applications
  • Part VII: Platform-Specific Support
  • Chapter 37: Windows
  • Chapter 38: UNIX-Compatible Modules
  • Appendix A: Online Resources
  • Appendix B: Python Development Environments
  • Index
  • Part I: The Python Language Acknowledgments xiv
  • Chapter 1: Python in an Hour
  • Jumping In: Starting the Python Interpreter
  • Experimenting with Variables and Expressions
  • Pocket calculator
  • Variables
  • Defining a Function
  • Running a Python Program
  • Looping and Control
  • Integer division
  • Looping
  • Branching with if-statements
  • Breaking and continuing
  • Lists and Tuples
  • Tuples
  • Slicing and dicing
  • Dictionaries
  • Reading and Writing Files
  • Sample Program: Word Frequencies
  • Loading and Using Modules
  • Creating a Class
  • Some quick object jargon
  • Object orientation, Python style
  • Keep off the grass — Accessing class members
  • Example: the point class
  • Recommended Reading
  • Chapter 2: Identifiers, Variables, and Numeric Types
  • Identifiers and Operators
  • Reserved words
  • Operators
  • Numeric Types
  • Integers
  • Long integers
  • Floating point numbers
  • Imaginary numbers xviii Python 2.1 Bible
  • Manipulating numeric types
  • Assigning Values to Variables
  • Simple assignment statements
  • Multiple assignment
  • Augmented assignment
  • Chapter 3: Expressions and Strings
  • Expressions
  • Comparing numeric types
  • Compound expressions
  • Complex expressions
  • Operator precedence
  • Strings
  • String literals
  • Manipulating strings
  • Comparing strings
  • Unicode string literals
  • Converting Between Simple Types
  • Converting to numerical types
  • Converting to strings
  • Chapter 4: Advanced Data Types
  • Grouping Data with Sequences
  • Creating lists
  • Creating tuples
  • Working with Sequences
  • Joining and repeating with arithmetic operators
  • Comparing and membership testing
  • Accessing parts of sequences
  • Iterating with for...in
  • Using sequence utility functions
  • Using Additional List Object Features
  • Additional operations
  • List object methods
  • Mapping Information with Dictionaries
  • Creating and adding to dictionaries
  • Accessing and updating dictionary mappings
  • Additional dictionary operations
  • Understanding References
  • Object identity
  • Counting references
  • Copying Complex Objects
  • Shallow copies
  • Deep copies
  • Identifying Data Types Contents xix
  • Working with Array Objects
  • Creating arrays
  • Converting between types
  • Array methods and operations
  • Chapter 5: Control Flow
  • Making Decisions with If-Statements
  • Using For-Loops
  • Anatomy of a for-loop
  • Looping example: encoding strings
  • Ranges and xranges
  • Breaking, continuing, and else-clauses
  • Changing horses in midstream
  • Using While-Loops
  • Throwing and Catching Exceptions
  • Passing the buck: propagating exceptions
  • Handling an exception
  • More on exceptions
  • Defining and raising exceptions
  • Cleaning up with finally
  • Debugging with Assertions
  • Assertions in Python
  • Toggling assertions
  • Example: Game of Life
  • Chapter 6: Program Organization
  • Defining Functions
  • Pass by object reference
  • All about parameters
  • Arbitrary arguments
  • Apply: passing arguments from a tuple
  • A bit of functional programming
  • Grouping Code with Modules
  • Laying out a module
  • Taking inventory of a module
  • Importing Modules
  • What else happens upon import?
  • Reimporting modules
  • Exotic imports
  • Locating Modules
  • Python path
  • Compiled files
  • Understanding Scope Rules
  • Is it local or global?
  • Listing namespace contents
  • Grouping Modules into Packages
  • Compiling and Running Programmatically