PYTHON - Programming Ebooks

8m ago
18 Views
0 Downloads
4.79 MB
384 Pages
Transcription

PYTHON PROJECTSINTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvCHAPTER 1Reviewing Core Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1CHAPTER 2Scripting with Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47CHAPTER 3Managing Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103CHAPTER 4Building Desktop Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161CHAPTER 5Python on the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223CHAPTER 6Python in Bigger Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257CHAPTER 7Exploring Python’s Frontiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285APPENDIX AAnswers to Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303APPENDIX BPython Standard Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319APPENDIX CUseful Python Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327REFERENCES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

Python Projects

Python ProjectsLaura CassellAlan Gauld

Python ProjectsPublished byJohn Wiley & Sons, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.comCopyright 2015 by John Wiley & Sons, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 978-1-118-90866-2ISBN: 978-1-118-90889-1 (ebk)ISBN: 978-1-118-90919-5 (ebk)Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means,electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorizationthrough payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers,MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to thePermissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201)748-6008, or online at http://www.wiley.com/go/permissions.Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties withrespect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, includingwithout limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales orpromotional materials. The advice and strategies contained herein may not be suitable for every situation. This workis sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professionalservices. If professional assistance is required, the services of a competent professional person should be sought. Neitherthe publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site isreferred to in this work as a citation and/or a potential source of further information does not mean that the author or thepublisher endorses the information the organization or Web site may provide or recommendations it may make. Further,readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when thiswork was written and when it is read.For general information on our other products and services please contact our Customer Care Department within theUnited States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included withstandard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to mediasuch as a CD or DVD that is not included in the version you purchased, you may download this material athttp://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.Library of Congress Control Number: 2014946683Trademarks: Wiley, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks orregistered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries, and maynot be used without written permission. Python is a registered trademark of Python Software Foundation Corporation.All other trademarks are the property of their respective owners. John Wiley & Sons, Inc., is not associated with anyproduct or vendor mentioned in this book.

For my truly great boys—Nathan, Ben, and Matt:We will do so many things now that I’m not writing.Thank you for all the quiet time while I was writing;you can come out of your rooms now.—Laura CassellTo my wife, Heather, for her continued support andpatience with my eccentric working hours.—Alan Gauld

ABOUT THE AUTHORSLAURA CASSELL has been poking at code on the web since 1997. She taught herself Perl in the early2000s where she discovered that programming materials were in dire need of an overhaul and thebarrier to entry to teach programming was incredibly high. Thus, her journey to learn programmingso she can bring it to other people began.Originally from Atlanta, GA, Laura founded PyLadies Atlanta, and got her start teaching Pythonand JavaScript for Big Nerd Ranch. She has since moved on to engineering management andcurrently resides in Portland, OR where she manages a team of Pythonistas doing software analyticsfor New Relic, Inc. She still volunteers for teaching and speaking gigs when time permits.ALAN GAULD is an enterprise architect with more than 40 years of experience in IT, workingmainly in the telecommunications and customer service areas. He has programmed in more than20 languages, producing everything from mainframe billing systems through embedded microcontrollers. For the last 15 years, his preference has been for Python. He is the author of a beginner’sbook on Python and is co-moderator of the python-tutor mailing list.When not programming, he likes climbing, backpacking, and skiing. He is also a keenphotographer, artist, and acoustic music enthusiast. He lives in Scotland with his wife, Heather.

ABOUT THE TECHNICAL EDITORSALEX BRADBURY is a compiler hacker, Linux geek, and Free Software enthusiast. He has beena long time contributor to the Raspberry Pi project and also co-authored Learning Python withRaspberry Pi. He is currently a researcher at the University of Cambridge Computer Laboratoryand is a co-founder of lowRISC, a non-profit project to produce a complete open-source Systemon-Chip (SoC).TODD SHANDELMAN fondly remembers coding assembly language programs on punch cardsfor IBM System/370 mainframes. After occupying various other ecological niches in softwaretechnology over the years (C, C , and Perl, to name but a few), Todd’s best days are now spentcoding pure Python 2.x and 3.x from the Linux command line. In his spare time he is a professionaltranslator of Russian and Hebrew, specializes in foreign-language typography, and can fi nd hisway in the dark around Unicode and UTF-8. Todd earned a Bachelor of Science degree in BusinessAdministration from the University of the State of New York. He lives in Houston, Texas, with hiswife and son.

CREDITSAcquisitions EditorJim MinatelProfessionalfTechnology & StrategyDirectorBarry PruettProject EditorJennifer LynnBusiness ManagerAmy KniesTechnical EditorsAlex BradburyTodd ShandelmanAssociate PublisherProduction EditorProject Coordinator, CoverChristine MugnoloPatrick RedmondCopy EditorProofreaderKimberly A. CoferSarah Kaikini, Word One New YorkProduction ManagerIndexerKathleen WisorJohnna DinseManager of Content Development andAssemblyCover DesignerJim MinatelWileyMary Beth WakefieldCover ImageMarketing DirectorDavid MayhewMarketing ManagerCarrie Sherrill iStock.com/skodonnell

ACKNOWLEDGMENTSI’D LIKE TO GIVE a big thank you to Alan Gauld, who helped put so much of this book together,and to Mary James and Jennifer Lynn for making sure this idea came to fruition. It’s a better bookbecause of all of you.Thank you also to the Python community, you are all the most welcoming community that I’veever found. You have created a place where people feel welcome and able to approach everyone,experts to novices alike. Keep up the good work and thank you for allowing me to be a part of thiswonderful community.—Laura CassellI’D LIKE TO GIVE a shout out to Laura Cassell for kick-starting this project, Jennifer Lynn forsteering us through it, and the Python community for their support over the last 15 years.—Alan Gauld

CONTENTSINTRODUCTIONCHAPTER 1: REVIEWING CORE PYTHONExploring the Python Language and the InterpreterReviewing the Python Data TypesNumeric Types: Integer and FloatThe Boolean TypeThe None TypeCollection TypesStringsBytes and ByteArraysTuplesListsDictionariesSetsUsing Python Control StructuresStructuring Your ProgramUsing Sequences, Blocks and CommentsSelecting an Execution PathIterationHandling ExceptionsManaging ContextGetting Data In and Out of PythonInteracting with UsersUsing Text FilesExtending PythonDefining and Using FunctionsGenerator FunctionsLambda FunctionsDefining and Using Classes and ObjectsCreating and Using Modules and PackagesUsing and Creating ModulesUsing and Creating PackagesCreating an Example PackageUsing Third‐Party 121232424262728333334364243

CONTENTSCHAPTER 2: SCRIPTING WITH PYTHONAccessing the Operating SystemObtaining Information About Users and Their ComputerObtaining Information About the Current ProcessManaging Other ProgramsManaging Subprocesses More EffectivelyObtaining Information About Files (and Devices)Navigating and Manipulating the File systemPlumbing the Directory Tree DepthsWorking with Dates and TimesUsing the time ModuleIntroducing the datetime ModuleIntroducing the calendar ModuleHandling Common File FormatsUsing Comma‐Separated ValuesWorking with Config FilesWorking with XML and HTML FilesParsing XML FilesParsing HTML FilesAccessing Native APIs with ctypes and pywin32Accessing the Operating System LibrariesUsing ctypes with WindowsUsing ctypes on LinuxAccessing a Windows Application Using utomating Tasks Involving Multiple Applications98Using Python FirstUsing Operating System UtilitiesUsing Data FilesUsing a Third‐Party ModuleInteracting with Subprocesses via a CLIUsing Web Services for Server‐Based ApplicationsUsing a Native Code APIUsing GUI Robotics989898999999100100Summary100CHAPTER 3: MANAGING DATA103Storing Data Using Python104Using DBM as a Persistent DictionaryUsing Pickle to Store and Retrieve ObjectsAccessing Objects with shelvexviii47104109111

CONTENTSAnalyzing Data with PythonAnalyzing Data Using Built‐In Features of PythonAnalyzing Data with ittertoolsUtility FunctionsData Processing FunctionsTaming the Vagaries of groupby()Using itertools to Analyze LendyDB DataManaging Data Using SQLRelational Database ConceptsStructured Query LanguageCreating TablesInserting DataReading DataModifying DataLinking Data Across TablesDigging Deeper into Data ConstraintsRevisiting SQLite Field TypesModeling Relationships with ConstraintsMany‐to‐Many RelationshipsMigrating LendyDB to an SQL 134134135136140143Accessing SQL from Python143Using SQL ConnectionsUsing a Cursor143143Creating the LendyDB SQL DatabaseInserting Test DataCreating a LendyDB APIExploring Other Data Management OptionsClient‐Server DatabasesNoSQLThe CloudData Analysis with RPySummaryCHAPTER 4: BUILDING DESKTOP APPLICATIONSStructuring ApplicationsBuilding Command-Line InterfacesBuilding the Data LayerBuilding the Core Logic LayerBuilding the User InterfaceUsing the cmd Module to Build a Command-Line InterfaceReading Command-Line 5169173175xix

CONTENTSJazzing Up the Command-Line Interface with Some DialogsProgramming GUIs with TkinterIntroducing Key GUI Principles181Event‐Based ProgrammingGUI TerminologyThe Containment Tree181182183Building a Simple GUIBuilding a Tic‐Tac‐Toe GUISketching a UI DesignBuilding MenusBuilding a Tic‐Tac‐Toe BoardConnecting the GUI to the GameExtending TkinterUsing TixUsing ttkRevisiting the Lending LibraryExploring Other GUI Toolkits for PythonwxPythonPyQtPyGTKNative GUIs: Cocoa and PyWin32DaboStoring Local DataStoring Application‐Specific DataStoring User‐Selected PreferencesStoring Application StateLogging Error 208209209210210211212212Understanding Localization214Using LocalesUsing Unicode in PythonUsing gettext214216218SummaryCHAPTER 5: PYTHON ON THE WEBPython on the WebParts of a Web ApplicationThe Client‐Server RelationshipMiddleware and MVCHTTP Methods and HeadersWhat Is an API?xx177181220223224225226226227230

CONTENTSWeb Programming with Python235Using the Python HTTP Modules235Creating an HTTP ServerExploring the Flask FrameworkCreating Data Models in FlaskCreating Core Flask Files235237238239More on Python and the Web247Static Site GeneratorsWeb FrameworksUsing Python Across the WireXML‐RPCSocket ServersMore Networking Fun in PythonSummaryCHAPTER 6: PYTHON IN BIGGER PROJECTSTesting with the Doctest ModuleTesting with the Unittest ModuleTest‐Driven Development in PythonDebugging Your Python CodeHandling Exceptions in PythonWorking on Larger Python ProjectsReleasing Python PackagesSummaryCHAPTER 7: EXPLORING PYTHON