Python Programming On Win32 - Zulfahmed - Free Download PDF

29d ago
4.91 MB
563 Pages

PythonProgrammingon Win32by Mark Hammond, AndyRobinsonISBN: 1-56592-621-8652 pages. January 2000.CoverTable of ContentsPrefacePart I — Introduction to PythonChapter 1 — What Is Python?Chapter 2 — Python LanguageReviewChapter 3 — Python on WindowsChapter 4 — IntegratedDevelopment Environments forPythonChapter 5 — Introduction toCOMPart II — Building an Advanced Python ApplicationChapter 6 — A Financial Modeling Toolkit in PythonChapter 7 — Building a GUI with COMChapter 8 — Adding a Macro LanguageChapter 9 — Integration with ExcelChapter 10 — Printed OutputChapter 11 — Distributing Our ApplicationPart III — Python on Windows CookbookChapter 12 — Advanced Python and COMChapter 13 — Databases

Chapter 14 — Working with EmailChapter 15 — Using the Basic Internet ProtocolsChapter 16 — Windows NT AdministrationChapter 17 — Processes and FilesChapter 18 — Windows NT ServicesChapter 19 — CommunicationsChapter 20 — GUI DevelopmentChapter 21 — Active ScriptingChapter 22 — Extending and Embedding with Visual C and DelphiPart IV — AppendixesAppendix A — Key Python Modules and FunctionsAppendix B — Win32 Extensions ReferenceAppendix C — The Python Database API Version 2.0Appendix D — Threads

Python Programming on Win32Mark Hammond and Andy RobinsonBeijing Cambridge Farnham Köln Paris Sebastopol Taipei TokyoPython Programming on Win32by Mark Hammond and Andy RobinsonCopyright 2000 O'Reilly & Associates, Inc. All rights reserved.Printed in the United States of America.Published by O'Reilly & Associates, Inc., 101 Morris Street, Sebastopol, CA 95472.Editor: Robert Denn

Production Editor: Mary Anne Weeks MayoCover Designer: Edie FreedmanPrinting History:January 2000:First Edition.Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks ofO'Reilly & Associates, Inc. The association between the image of a caiman and the topic ofprogramming Python on Win32 is a trademark of O'Reilly & Associates, Inc.Many of the designations used by manufacturers and sellers to distinguish their products are claimedas trademarks. Where those designations appear in this book, and O'Reilly & Associates, Inc. wasaware 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 assumes noresponsibility for errors or omissions, or for damages resulting from the use of the informationcontained herein.ISBN: 1-56592-621-8[M]Back

TABLE OF CONTENTSPrefaceI. Introduction to Python1. What Is Python?Language FeaturesPython as an Integration ToolCase Studies of Python DeploymentThe Python CommunityInstallation and SetupConclusion2. Python Language ReviewA Crash CourseConclusionReferences3. Python on WindowsThe Python Core on WindowsThe Python for Windows Extensions

The Python Imaging Library (PIL)PyOpenGLWeb Publishing ToolsThe mx ExtensionsScientific ToolsXMLConclusion4. Integrated Development Environments for PythonThe PythonWin IDEIDLEConclusion5. Introduction to COMWhat It IsUsing COM Objects from PythonImplementing COM Objects with PythonGlobally Unique IdentifiersConclusion

II. Building an Advanced Python Application6. A Financial Modeling Toolkit in PythonDoubletalkA Crash Course in AccountingThe Doubletalk Toolkit at WorkConclusion7. Building a GUI with COMDesigning COM ServersA VB ClientWriting a Delphi User InterfaceConclusion8. Adding a Macro LanguageDynamic Code EvaluationMaking an Application ExtensibleConclusion9. Integration with ExcelClient-Side COM and the Excel Object Model

Excel ConcludedPutting It All Together: Importing Financial DataServer-Side COM Again: Excel as a GUIConclusionReferences10. Printed OutputBusiness RequirementsAutomating WordDirect Output to the Printer with WindowsPIDDLE: A Python Graphics APIPostScriptPortable Document FormatPutting It Together: A High-Volume Invoicing SystemConclusionReferences11. Distributing Our ApplicationDCOM

ConclusionIII. Python on Windows Cookbook12. Advanced Python and COMAdvanced COMPython and COMUsing Automation Objects from PythonUsing Other COM InterfacesError HandlingImplementing COM Objects in PythonPython and DCOMConclusion13. DatabasesDAO, ADO, ODBC, OLEDB, and Other GBFLAsPython's Database APIGetting at Your DataA Note on SpeedGadfly, the Pure Python Relational Database

Data Laundering with PythonA Three-Tier Architecture with Business ObjectsConclusionReferences14. Working with EmailSMTP and POP3Microsoft Exchange/OutlookConclusion15. Using the Basic Internet ProtocolsHTTP and HTMLFTPNNTPConclusion16. Windows NT AdministrationWorking with Users and GroupsServer and Share InformationRebooting a Machine

ConclusionReferences17. Processes and FilesPortable File ManipulationNative File Manipulation: The win32file ModulePipesProcessesConclusion18. Windows NT ServicesServices in BriefControlling Services with PythonReading the Event LogWindows NT Performance Monitor DataWriting Services in PythonSample Service Written in PythonWriting to the Event LogProviding Performance Monitor Information

A Final ServiceConclusion19. CommunicationsSerial CommunicationsRemote Access ServicesSocketsOther Communications ToolsConclusionReferences20. GUI DevelopmentTkinterPythonWinwxPython21. Active ScriptingRegistering the Python Active Script SupportPython and Popular Microsoft ApplicationsActive Debugging

How Active Scripting WorksActive Script Hosting in PythonConclusion22. Extending and Embedding with Visual C and DelphiPython and Visual C Simplified Wrapper and Interface GeneratorPython and DelphiDynamic DLL AccessReferencesConclusionIV. AppendixesA. Key Python Modules and FunctionsB. Win32 Extensions ReferenceC. The Python Database API Version 2.0D. ThreadsIndexBack

PREFACEAbout This BookThis book is about using Python to get jobs done onWindows.We hope by now you have heard of Python, the excitingobject-oriented scripting language that is rapidly enteringthe programming mainstream. Although Python is perhapsbetter known on the Unix platform, it offers a superb degreeof integration with the Windows environment. One of us,Mark Hammond, is responsible for many of Python'sWindows extensions and has coauthored the Python COMsupport, both of which are major topics of this book. Thisbook can thus be considered the definitive reference to date for Python on the Windows platform.This is intended to be a practical book focused on tasks. It doesn't aim to teach Python programming,although we do provide a brief tutorial. Instead, it aims to cover: How Python works on Windows The key integration technologies supported by Python on Windows, such as the Win32 extensions,which let you call the Windows API, and the support for COM Examples in many topic areas showing what Python can do and how to put it to workIn the end, we hope you will have a clear idea of what Python can do and how to put it to work onreal-world tasks.Who Is This Book for?We expect this book to be of interest to two groups of people:Windows developers, administrators, and IT managersYou may be an experienced Windows developer using C , Visual Basic, Delphi or otherdevelopment tools, or you may be involved in managing information technology (IT) and need tomake decisions as to the right tools for large projects. No doubt you hear about several newlanguages every year and meet zealots who insist that each is the ultimate development tool. You'veperhaps heard a colleague talking about Python or read a few articles about it and are curious whypeople rave about it. By the end of this book, you should know!

Python converts from UnixPython is one of the major products of the Open Source revolution ( and has alarge following on Unix platforms. There are a large number of Python users within the Unixtradition who are forced, with varying degrees of resistance, to work in a Windows environment. Wehope to open your eyes. Most of the things you do on Unix can be done on Windows, and Windowsoffers exciting programming possibilities.Readers may vary considerably in their programming experience. We don't aim to teach the languagesystematically and assume you are familiar with other programming languages. Someone familiarwith Visual Basic, for example, should be able to follow most of the book. However, some sectionsregarding Windows internals or C integration assume C or C familiarity.We assume a fairly typical business-computing platform with Windows NT 4.0, Microsoft Office,access to the Internet or an internal TCP/IP network, and adequate memory to run smoothly. Pythonis equally happy on Windows 95 and 98, and we have tried to comment on the differences as theyoccur.How the Book Is OrganizedThe book is broken into three parts. The first part is mainly introductory in nature and sets theframework for the other two sections. The second section focuses on building an advanced Windowsapplication using Python. The main purpose of this application is to show some possibilities for yourapplications. The third section provides a Python on Windows cookbook.Part I, Introduction to PythonThis part covers the basics about the language and the platform and should be read by everyone notfamiliar with using Python on Windows.Chapter 1, What Is Python?This is a Python primer: what it's good for, who's using it for what, and where to get hold of it. If youwant to brief your manager on Python, show her this chapter!Chapter 2, Python Language ReviewThis chapter is a high-speed minitutorial; it should at least enable you to follow the code examples.We don't aim to teach Python from scratch, but instead point you to the right places for more detailedtutorials.Chapter 3, Python on WindowsHere we cover how Python is set up on Windows and review some of the Windows-specific packagesand extensions.Chapter 4, Integrated Development Environments for Python

Chapter 4 covers PythonWin and IDLE, two integrated development environments for Python, eachcomplete with syntax coloring, object browsers, and debuggers.Chapter 5, Introduction to COMHere we introduce Python's support for COM, Microsoft's key integration technology.Part II, Building an Advanced Python ApplicationThis part is an in-depth exploration of what you can do with a Python application on Windows.''Advanced'' refers to the capabilities Python gives to your programs, not to the level of programmingdifficulty. Although the focus is on COM, it brings many features of the language together. In somecases, we use features not fully explained until later chapters; we want to make you say "Wow, soyou can do that," rather than "Wow, so that's how you do it": we save that revelation for the lastsection. The project is to develop an extensible accounting toolkit in Python. Part II, like Part I, isintended to be read straight through.Chapter 6, A Financial Modeling Toolkit in PythonThis chapter explains the business requirements of our application and develops a Python classlibrary that encapsulates the basic rules followed by accounting systems. For people new to Python,this provides a more in-depth set of examples of object-oriented programming with Python.Chapter 7, Building a GUI with COMHere we show how to build a COM server that exposes our Python "engine" to other applications,building a fairly standard user interface in Visual Basic on top our application. In the process, wecover how to move data of all types back and forth between Python and other languages using COM.Chapter 8, Adding a Macro LanguageNext we show how to expose the Python interpreter to end users. Our application allows users towork with a command prompt, write scripts, and even define new event handlers and graphicalviews, thereby making the application extensible. Python makes this capability, normally found onlyin large commercial applications, child's play.Chapter 9, Integration with ExcelThis chapter shows the other side of the coin: using Python as a COM object to acquire data from andsend data to Excel.Chapter 10, Printed OutputHere we cover a range of techniques for printing and for producing reports in general, includingdirect printer control, automating Microsoft Word, and direct generation of financial reports in PDFformat.Chapter 11, Distributing Our ApplicationFinally, we show how COM makes it extremely easy to run the Python engine on one machine andthe client interface on another.

Part III, Python on Windows CookbookEach chapter in this section may be taken in isolation and covers one particular area of interest indetail. The focus is task-based, and we look at various technologies and libraries in each section,concentrating on how to get jobs done with Python. These chapters naturally vary in their technicaldepth and appeal, but we hope that there will be plenty of interest for everyone.Chapter 12, Advanced Python and COMThis is the definitive reference on Python's support for COM.Chapter 13, DatabasesThis chapter shows how to connect to databases from Python and illustrates how to manipulate data.Chapter 14, Working with EmailHere we take a look at some common techniques for dealing with email on Windows.Chapter 15, Using the Basic Internet ProtocolsThis is a brief discussion on how to use common Internet protocols from Python on Windows.Chapter 16, Windows NT AdministrationIn this chapter, we discuss the language extensions for working with users, groups, drives, shares,servers, and so forth.Chapter 17, Processes and FilesThis chapter presents Python's facilities for working with processes and files, both in a portable and aWindows-specific way.Chapter 18, Windows NT ServicesHere we explore Python's thorough support for Windows NT services.Chapter 19, CommunicationsThis chapter discusses serial I/O, remote access services, and TCP/IP sockets.Chapter 20, GUI DevelopmentHere we present three toolkits: PythonWin, Tkinter, and wxPython.Chapter 21, Active ScriptingThis chapter presents a complete guide

It doesn't aim to teach Python programming, although we do provide a brief tutorial. Instead, it aims to cover: • How Python works on Windows • The key integration technologies supported by Python on Windows, such as the Win32 extensions, which let you call the Windows API, and the support for COM • Examples in many topic areas showing what Python can do and how to put it to work In the ...