Tài liệu Programming python 4th edition

  • Số trang: 1628 |
  • Loại file: PDF |
  • Lượt xem: 227 |
  • Lượt tải: 0
minhminh

Đã đăng 411 tài liệu

Mô tả:

www.it-ebooks.info www.it-ebooks.info Programming Python www.it-ebooks.info www.it-ebooks.info FOURTH EDITION Programming Python Mark Lutz Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo www.it-ebooks.info Programming Python, Fourth Edition by Mark Lutz Copyright © 2011 Mark Lutz. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://my.safaribooksonline.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Julie Steele Production Editor: Teresa Elsey Proofreader: Teresa Elsey Indexer: Lucie Haskins Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Printing History: October 1996: March 2001: August 2006: December 2010: First Edition. Second Edition. Third Edition. Fourth Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Programming Python, the image of an African rock python, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-0-596-15810-1 [QG] 1292258056 www.it-ebooks.info Table of Contents Download from Wow! eBook Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii Part I. The Beginning 1. A Sneak Preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 “Programming Python: The Short Story” The Task Step 1: Representing Records Using Lists Using Dictionaries Step 2: Storing Records Persistently Using Formatted Files Using Pickle Files Using Per-Record Pickle Files Using Shelves Step 3: Stepping Up to OOP Using Classes Adding Behavior Adding Inheritance Refactoring Code Adding Persistence Other Database Options Step 4: Adding Console Interaction A Console Shelve Interface Step 5: Adding a GUI GUI Basics Using OOP for GUIs Getting Input from a User A GUI Shelve Interface Step 6: Adding a Web Interface CGI Basics 3 4 4 4 9 14 14 19 22 23 26 27 29 29 31 34 36 37 37 40 40 42 44 46 52 52 v www.it-ebooks.info Running a Web Server Using Query Strings and urllib Formatting Reply Text A Web-Based Shelve Interface The End of the Demo 55 57 59 60 69 Part II. System Programming 2. System Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 “The os.path to Knowledge” Why Python Here? The Next Five Chapters System Scripting Overview Python System Modules Module Documentation Sources Paging Documentation Strings A Custom Paging Script String Method Basics Other String Concepts in Python 3.X: Unicode and bytes File Operation Basics Using Programs in Two Ways Python Library Manuals Commercially Published References Introducing the sys Module Platforms and Versions The Module Search Path The Loaded Modules Table Exception Details Other sys Module Exports Introducing the os Module Tools in the os Module Administrative Tools Portability Constants Common os.path Tools Running Shell Commands from Scripts Other os Module Exports 73 73 74 75 76 77 78 79 80 82 83 84 85 86 86 86 87 88 89 90 90 90 91 92 92 94 100 3. Script Execution Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 “I’d Like to Have an Argument, Please” Current Working Directory CWD, Files, and Import Paths CWD and Command Lines vi | Table of Contents www.it-ebooks.info 103 104 104 106 Command-Line Arguments Parsing Command-Line Arguments Shell Environment Variables Fetching Shell Variables Changing Shell Variables Shell Variable Fine Points: Parents, putenv, and getenv Standard Streams Redirecting Streams to Files and Programs Redirected Streams and User Interaction Redirecting Streams to Python Objects The io.StringIO and io.BytesIO Utility Classes Capturing the stderr Stream Redirection Syntax in Print Calls Other Redirection Options: os.popen and subprocess Revisited 106 107 109 110 111 112 113 114 119 123 126 127 127 128 4. File and Directory Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 “Erase Your Hard Drive in Five Easy Steps!” File Tools The File Object Model in Python 3.X Using Built-in File Objects Binary and Text Files Lower-Level File Tools in the os Module File Scanners Directory Tools Walking One Directory Walking Directory Trees Handling Unicode Filenames in 3.X: listdir, walk, glob 135 135 136 137 146 155 160 163 164 168 172 5. Parallel System Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 “Telling the Monkeys What to Do” Forking Processes The fork/exec Combination Threads The _thread Module The threading Module The queue Module Preview: GUIs and Threads More on the Global Interpreter Lock Program Exits sys Module Exits os Module Exits Shell Command Exit Status Codes Process Exit Status and Shared State 177 179 182 186 189 199 204 208 211 213 214 215 216 219 Table of Contents | vii www.it-ebooks.info Thread Exits and Shared State Interprocess Communication Anonymous Pipes Named Pipes (Fifos) Sockets: A First Look Signals The multiprocessing Module Why multiprocessing? The Basics: Processes and Locks IPC Tools: Pipes, Shared Memory, and Queues Starting Independent Programs And Much More Why multiprocessing? The Conclusion Other Ways to Start Programs The os.spawn Calls The os.startfile call on Windows A Portable Program-Launch Framework Other System Tools Coverage 220 222 224 234 236 240 243 243 245 248 254 256 257 258 258 261 263 268 6. Complete System Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 “The Greps of Wrath” A Quick Game of “Find the Biggest Python File” Scanning the Standard Library Directory Scanning the Standard Library Tree Scanning the Module Search Path Scanning the Entire Machine Printing Unicode Filenames Splitting and Joining Files Splitting Files Portably Joining Files Portably Usage Variations Generating Redirection Web Pages Page Template File Page Generator Script A Regression Test Script Running the Test Driver Copying Directory Trees Comparing Directory Trees Finding Directory Differences Finding Tree Differences Running the Script Verifying Backups Reporting Differences and Other Ideas viii | Table of Contents www.it-ebooks.info 271 272 272 273 274 276 279 282 283 286 289 292 293 294 297 299 304 308 309 311 314 316 317 Searching Directory Trees Greps and Globs and Finds Rolling Your Own find Module Cleaning Up Bytecode Files A Python Tree Searcher Visitor: Walking Directories “++” Editing Files in Directory Trees (Visitor) Global Replacements in Directory Trees (Visitor) Counting Source Code Lines (Visitor) Recoding Copies with Classes (Visitor) Other Visitor Examples (External) Playing Media Files The Python webbrowser Module The Python mimetypes Module Running the Script Automated Program Launchers (External) 319 320 321 324 327 330 334 336 338 339 341 343 347 348 350 351 Part III. GUI Programming 7. Graphical User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 “Here’s Looking at You, Kid” GUI Programming Topics Running the Examples Python GUI Development Options tkinter Overview tkinter Pragmatics tkinter Documentation tkinter Extensions tkinter Structure Climbing the GUI Learning Curve “Hello World” in Four Lines (or Less) tkinter Coding Basics Making Widgets Geometry Managers Running GUI Programs tkinter Coding Alternatives Widget Resizing Basics Configuring Widget Options and Window Titles One More for Old Times’ Sake Packing Widgets Without Saving Them Adding Buttons and Callbacks Widget Resizing Revisited: Expansion 355 355 357 358 363 363 364 364 366 368 368 369 370 370 371 372 373 375 376 377 379 380 Table of Contents | ix www.it-ebooks.info Adding User-Defined Callback Handlers Lambda Callback Handlers Deferring Calls with Lambdas and Object References Callback Scope Issues Bound Method Callback Handlers Callable Class Object Callback Handlers Other tkinter Callback Protocols Binding Events Adding Multiple Widgets Widget Resizing Revisited: Clipping Attaching Widgets to Frames Layout: Packing Order and Side Attachments The Packer’s Expand and Fill Revisited Using Anchor to Position Instead of Stretch Customizing Widgets with Classes Standardizing Behavior and Appearance Reusable GUI Components with Classes Attaching Class Components Extending Class Components Standalone Container Classes The End of the Tutorial Python/tkinter for Tcl/Tk Converts 382 383 384 385 391 392 393 394 395 396 397 397 398 399 400 401 403 405 407 408 410 412 8. A tkinter Tour, Part 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415 “Widgets and Gadgets and GUIs, Oh My!” This Chapter’s Topics Configuring Widget Appearance Top-Level Windows Toplevel and Tk Widgets Top-Level Window Protocols Dialogs Standard (Common) Dialogs The Old-Style Dialog Module Custom Dialogs Binding Events Other bind Events Message and Entry Message Entry Laying Out Input Forms tkinter “Variables” and Form Layout Alternatives Checkbutton, Radiobutton, and Scale Checkbuttons x | Table of Contents www.it-ebooks.info 415 415 416 419 421 422 426 426 438 439 443 447 448 448 449 451 454 457 457 Radio Buttons Scales (Sliders) Running GUI Code Three Ways Attaching Frames Independent Windows Running Programs Images Fun with Buttons and Pictures Viewing and Processing Images with PIL PIL Basics Displaying Other Image Types with PIL Creating Image Thumbnails with PIL 462 467 471 471 476 478 484 487 491 491 493 496 9. A tkinter Tour, Part 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507 “On Today’s Menu: Spam, Spam, and Spam” Menus Top-Level Window Menus Frame- and Menubutton-Based Menus Windows with Both Menus and Toolbars Listboxes and Scrollbars Programming Listboxes Programming Scroll Bars Packing Scroll Bars Text Programming the Text Widget Adding Text-Editing Operations Unicode and the Text Widget Advanced Text and Tag Operations Canvas Basic Canvas Operations Programming the Canvas Widget Scrolling Canvases Scrollable Canvases and Image Thumbnails Using Canvas Events Grids Why Grids? Grid Basics: Input Forms Revisited Comparing grid and pack Combining grid and pack Making Gridded Widgets Expandable Laying Out Larger Tables with grid Time Tools, Threads, and Animation Using Threads with tkinter GUIs 507 507 508 512 517 522 524 525 526 528 530 533 538 548 550 550 551 554 557 560 564 564 565 566 568 570 574 582 584 Table of Contents | xi www.it-ebooks.info Using the after Method Simple Animation Techniques Other Animation Topics The End of the Tour Other Widgets and Options 585 588 593 595 595 10. GUI Coding Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597 “Building a Better Mousetrap” GuiMixin: Common Tool Mixin Classes Widget Builder Functions Mixin Utility Classes GuiMaker: Automating Menus and Toolbars Subclass Protocols GuiMaker Classes GuiMaker Self-Test BigGui: A Client Demo Program ShellGui: GUIs for Command-Line Tools A Generic Shell-Tools Display Application-Specific Tool Set Classes Adding GUI Frontends to Command Lines GuiStreams: Redirecting Streams to Widgets Using Redirection for the Packing Scripts Reloading Callback Handlers Dynamically Wrapping Up Top-Level Window Interfaces GUIs, Threads, and Queues Placing Data on Queues Placing Callbacks on Queues More Ways to Add GUIs to Non-GUI Code Popping Up GUI Windows on Demand Adding a GUI As a Separate Program: Sockets (A Second Look) Adding a GUI As a Separate Program: Command Pipes The PyDemos and PyGadgets Launchers PyDemos Launcher Bar (Mostly External) PyGadgets Launcher Bar 597 598 598 599 603 607 608 608 609 613 613 615 617 623 627 628 630 635 636 640 646 647 649 654 662 662 667 11. Complete GUI Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671 “Python, Open Source, and Camaros” Examples in Other Chapters This Chapter’s Strategy PyEdit: A Text Editor Program/Object Running PyEdit PyEdit Changes in Version 2.0 (Third Edition) PyEdit Changes in Version 2.1 (Fourth Edition) xii | Table of Contents www.it-ebooks.info 671 672 673 674 675 682 684 PyEdit Source Code PyPhoto: An Image Viewer and Resizer Running PyPhoto PyPhoto Source Code PyView: An Image and Notes Slideshow Running PyView PyView Source Code PyDraw: Painting and Moving Graphics Running PyDraw PyDraw Source Code PyClock: An Analog/Digital Clock Widget A Quick Geometry Lesson Running PyClock PyClock Source Code PyToe: A Tic-Tac-Toe Game Widget Running PyToe PyToe Source Code (External) Where to Go from Here 693 716 717 719 727 727 732 738 738 738 747 747 751 754 762 762 763 766 Part IV. Internet Programming 12. Network Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771 “Tune In, Log On, and Drop Out” Internet Scripting Topics Running Examples in This Part of the Book Python Internet Development Options Plumbing the Internet The Socket Layer The Protocol Layer Python’s Internet Library Modules Socket Programming Socket Basics Running Socket Programs Locally Running Socket Programs Remotely Spawning Clients in Parallel Talking to Reserved Ports Handling Multiple Clients Forking Servers Threading Servers Standard Library Server Classes Multiplexing Servers with select Summary: Choosing a Server Scheme 771 772 775 777 780 781 782 785 787 788 794 795 798 801 802 803 815 818 820 826 Table of Contents | xiii www.it-ebooks.info Making Sockets Look Like Files and Streams A Stream Redirection Utility A Simple Python File Server Running the File Server and Clients Adding a User-Interface Frontend 827 828 840 842 843 13. Client-Side Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853 “Socket to Me!” FTP: Transferring Files over the Net Transferring Files with ftplib Using urllib to Download Files FTP get and put Utilities Adding a User Interface Transferring Directories with ftplib Downloading Site Directories Uploading Site Directories Refactoring Uploads and Downloads for Reuse Transferring Directory Trees with ftplib Uploading Local Trees Deleting Remote Trees Downloading Remote Trees Processing Internet Email Unicode in Python 3.X and Email Tools POP: Fetching Email Mail Configuration Module POP Mail Reader Script Fetching Messages Fetching Email at the Interactive Prompt SMTP: Sending Email SMTP Mail Sender Script Sending Messages Sending Email at the Interactive Prompt email: Parsing and Composing Mail Content Message Objects Basic email Package Interfaces in Action Unicode, Internationalization, and the Python 3.1 email Package A Console-Based Email Client Running the pymail Console Client The mailtools Utility Package Initialization File MailTool Class MailSender Class MailFetcher Class xiv | Table of Contents www.it-ebooks.info 853 854 854 857 860 867 874 874 880 884 892 893 895 899 899 900 901 902 905 906 909 910 911 913 919 921 922 924 926 947 952 956 957 958 959 967 MailParser Class Self-Test Script Updating the pymail Console Client NNTP: Accessing Newsgroups HTTP: Accessing Websites The urllib Package Revisited Other urllib Interfaces Other Client-Side Scripting Options 976 983 986 991 994 997 999 1002 14. The PyMailGUI Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1005 “Use the Source, Luke” Source Code Modules and Size Why PyMailGUI? Running PyMailGUI Presentation Strategy Major PyMailGUI Changes New in Version 2.1 and 2.0 (Third Edition) New in Version 3.0 (Fourth Edition) A PyMailGUI Demo Getting Started Loading Mail Threading Model Load Server Interface Offline Processing with Save and Open Sending Email and Attachments Viewing Email and Attachments Email Replies and Forwards and Recipient Options Deleting Email POP Message Numbers and Synchronization Handling HTML Content in Email Mail Content Internationalization Support Alternative Configurations and Accounts Multiple Windows and Status Messages PyMailGUI Implementation PyMailGUI: The Main Module SharedNames: Program-Wide Globals ListWindows: Message List Windows ViewWindows: Message View Windows messagecache: Message Cache Manager popuputil: General-Purpose GUI Pop Ups wraplines: Line Split Tools html2text: Extracting Text from HTML (Prototype, Preview) mailconfig: User Configurations 1005 1006 1008 1010 1010 1011 1011 1012 1019 1020 1025 1027 1030 1031 1033 1037 1043 1049 1051 1053 1055 1059 1060 1062 1063 1066 1067 1085 1095 1098 1100 1102 1105 Table of Contents | xv www.it-ebooks.info textConfig: Customizing Pop-Up PyEdit Windows PyMailGUIHelp: User Help Text and Display altconfigs: Configuring for Multiple Accounts Ideas for Improvement 1110 1111 1114 1116 15. Server-Side Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1125 “Oh, What a Tangled Web We Weave” What’s a Server-Side CGI Script? The Script Behind the Curtain Writing CGI Scripts in Python Running Server-Side Examples Web Server Options Running a Local Web Server The Server-Side Examples Root Page Viewing Server-Side Examples and Output Climbing the CGI Learning Curve A First Web Page A First CGI Script Adding Pictures and Generating Tables Adding User Interaction Using Tables to Lay Out Forms Adding Common Input Devices Changing Input Layouts Passing Parameters in Hardcoded URLs Passing Parameters in Hidden Form Fields Saving State Information in CGI Scripts URL Query Parameters Hidden Form Input Fields HTTP “Cookies” Server-Side Databases Extensions to the CGI Model Combining Techniques The Hello World Selector Checking for Missing and Invalid Inputs Refactoring Code for Maintainability Step 1: Sharing Objects Between Pages—A New Input Form Step 2: A Reusable Form Mock-Up Utility Step 3: Putting It All Together—A New Reply Script More on HTML and URL Escapes URL Escape Code Conventions Python HTML and URL Escape Tools Escaping HTML Code Escaping URLs xvi | Table of Contents www.it-ebooks.info 1125 1126 1126 1128 1130 1130 1131 1133 1134 1135 1135 1141 1146 1149 1157 1163 1166 1170 1172 1174 1176 1176 1177 1181 1182 1183 1183 1190 1192 1193 1196 1199 1201 1202 1203 1203 1204 Escaping URLs Embedded in HTML Code Transferring Files to Clients and Servers Displaying Arbitrary Server Files on the Client Uploading Client Files to the Server More Than One Way to Push Bits over the Net 1205 1209 1211 1218 1227 16. The PyMailCGI Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1229 “Things to Do When Visiting Chicago” The PyMailCGI Website Implementation Overview New in This Fourth Edition (Version 3.0) New in the Prior Edition (Version 2.0) Presentation Overview Running This Chapter’s Examples The Root Page Configuring PyMailCGI Sending Mail by SMTP The Message Composition Page The Send Mail Script Error Pages Common Look-and-Feel Using the Send Mail Script Outside a Browser Reading POP Email The POP Password Page The Mail Selection List Page Passing State Information in URL Link Parameters Security Protocols The Message View Page Passing State Information in HTML Hidden Input Fields Escaping Mail Text and Passwords in HTML Processing Fetched Mail Reply and Forward Delete Deletions and POP Message Numbers Utility Modules External Components and Configuration POP Mail Interface POP Password Encryption Common Utilities Module Web Scripting Trade-Offs PyMailCGI Versus PyMailGUI The Web Versus the Desktop Other Approaches 1229 1230 1230 1233 1235 1236 1237 1239 1240 1241 1242 1242 1246 1246 1247 1249 1250 1251 1254 1257 1259 1262 1264 1266 1267 1268 1272 1276 1276 1277 1278 1286 1291 1292 1293 1296 Table of Contents | xvii www.it-ebooks.info Part V. Tools and Techniques 17. Databases and Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1303 “Give Me an Order of Persistence, but Hold the Pickles” Persistence Options in Python DBM Files Using DBM Files DBM Details: Files, Portability, and Close Pickled Objects Using Object Pickling Pickling in Action Pickle Details: Protocols, Binary Modes, and _pickle Shelve Files Using Shelves Storing Built-in Object Types in Shelves Storing Class Instances in Shelves Changing Classes of Objects Stored in Shelves Shelve Constraints Pickled Class Constraints Other Shelve Limitations The ZODB Object-Oriented Database The Mostly Missing ZODB Tutorial SQL Database Interfaces SQL Interface Overview An SQL Database API Tutorial with SQLite Building Record Dictionaries Tying the Pieces Together Loading Database Tables from Files SQL Utility Scripts SQL Resources ORMs: Object Relational Mappers PyForm: A Persistent Object Viewer (External) 1303 1303 1305 1305 1308 1309 1310 1311 1314 1315 1316 1317 1318 1320 1321 1323 1324 1325 1326 1329 1330 1332 1339 1342 1344 1347 1354 1354 1356 18. Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1359 “Roses Are Red, Violets Are Blue; Lists Are Mutable, and So Is Set Foo” Implementing Stacks Built-in Options A Stack Module A Stack Class Customization: Performance Monitors Optimization: Tuple Tree Stacks xviii | Table of Contents www.it-ebooks.info 1359 1360 1360 1362 1364 1366 1367
- Xem thêm -