Showing posts with label Programming Book. Show all posts

Dan Bader

What Pythonistas Say About Python Tricks: The Book

”I love love love the book. It’s like having a seasoned tutor explaining,
well, tricks! I’m learning Python on the job and I’m coming from powershell,
which I learned on the job—so lots of new, great stuff. Whenever
I get stuck in Python (usually with flask blueprints or I feel like my
code could be more Pythonic) I post questions in our internal Python chat room.
I’m often amazed at some of the answers coworkers give me. Dict comprehensions,
lambdas, and generators often pepper their feedback. I
am always impressed and yet flabbergasted at how powerful Python
is when you know these tricks and can implement them correctly.
Your book was exactly what I wanted to help get me from a bewildered
powershell scripter to someone who knows how and when to use these
Pythonic ‘tricks’ everyone has been talking about.
As someone who doesn’t have my degree in CS it’s nice to have the text
to explain things that others might have learned when they were classically
educated. I am really enjoying the book and am subscribed to
the emails as well, which is how I found out about the book.”
— Daniel Meyer, Sr. Desktop Administrator at Tesla Inc.

”I first heard about your book from a co-worker who wanted to
trick me with your example of how dictionaries are built. I was
almost 100% sure about the reason why the end product was a much
smaller/simpler dictionary but I must confess that 
I did not expect the outcome :)
He showed me the book via video conferencing and I sort of skimmed
through it as he flipped the pages for me, and I was immediately curious to read more.
That same afternoon I purchased my own copy and proceeded to read
your explanation for the way dictionaries are created in Python and
later that day, as I met a different co-worker for coffee, 
I used the same trick on him :)
He then sprung a different question on the same principle, and because
of the way you explained things in your book, I was able tonot*
guess the result but correctly answer what the outcome would be. That
means that you did a great job at explaining things :)*
I am not new in Python and some of the concepts in some of the chapters
are not new to me, but I must say that I do get something out of
every chapter so far, so kudos for writing a very nice book and for doing
a fantastic job at explaining concepts behind the tricks! I’m very
much looking forward to the updates and I will certainly let my friends
and co-workers know about your book.”
— Og Maciel, Python Developer at Red Hat

”I really enjoyed reading Dan’s book. He explains important Python
aspects with clear examples (using two twin cats to explain ‘is‘ vs ‘==‘
for example).
It is not just code samples, it discusses relevant implementation details
comprehensibly. What really matters though is that this book makes
you write better Python code!
The book is actually responsible for recent new good Python habits I
picked up, for example: using custom exceptions and ABC’s (I found
Dan’s blog searching for abstract classes.) These new learnings alone
are worth the price.”
— Bob Belderbos, Engineer at Oracle & Co-Founder of PyBites

e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 3.00
 Pages
 299 p
 File Size 
 1,276 KB
 File Type
 PDF format
 ISBN
 9781775093305 (paperback)
 9781775093312 (electronic)
 Copyright©   
 Dan Bader (dbader.org), 2016–2017   

Foreword
It’s been almost ten years since I first got acquainted with Python as a
programming language. When I first learned Python many years ago,
it was with a little reluctance. I had been programming in a different
language before, and all of the sudden at work, I was assigned to a
different team where everyone used Python. That was the beginning
of my own Python journey.
When I was first introduced to Python, I was told that it was going to
be easy, that I should be able to pick it up quickly. When I asked my
colleagues for resources for learning Python, all they gave me was a
link to Python’s official documentation. Reading the documentation
was confusing at first, and it really took me a while before I even felt
comfortable navigating through it. Often I found myself needing to
look for answers in StackOverflow.
Coming from a different programming language, I wasn’t looking for
just any resource for learning how to program or what classes and
objects are. I was looking for specific resources that would teach me
the features of Python, what sets it apart, and how writing in Python
is different than writing code in another language.
It really has taken me many years to fully appreciate this language. As
I read Dan’s book, I kept thinking that I wished I had access to a book
like this when I started learning Python many years ago.
For example, one of the many unique Python features that surprised
me at first were list comprehensions. As Dan mentions in the book,
a tell of someone who just came to Python from a different language
is the way they use for-loops. I recall one of the earliest code review
comments I got when I started programming in Python was, “Why
not use list comprehension here?” Dan explains this concept clearly
in section 6, starting by showing how to loop the Pythonic way and
building it all the way up to iterators and generators.
In chapter 2.5, Dan discusses the different ways to do string formatting
in Python. String formatting is one of those things that defy the
Zen of Python, that there should only be one obvious way to do things.
Dan shows us the different ways, including my favorite new addition
to the language, the f-strings, and he also explains the pros and cons
of each method.
The Pythonic Productivity Techniques section is another great resource.
It covers aspects beyond the Python programming language,
and also includes tips on how to debug your programs, how to manage
the dependencies, and gives you a peek inside Python bytecode.
It truly is an honor and my pleasure to introduce this book, Python
Tricks, by my friend, Dan Bader.
By contributing to Python as a CPython core developer, I get connected
to many members of the community. In my journey, I found
mentors, allies, and made many new friends. They remind me that
Python is not just about the code, Python is a community.
Mastering Python programming isn’t just about grasping the theoretical
aspects of the language. It’s just as much about understanding and
adopting the conventions and best practices used by its community.
Dan’s book will help you on this journey. I’m convinced that you’ll be
more confident when writing Python programs after reading it.
— Mariatta Wijaya, Python Core Developer (mariatta.ca)

Table of Contents
Contents 6
Foreword 9
1 Introduction 11
1.1 What’s a Python Trick? . . . . . . . . . . . . . . . . 11
1.2 What This Book Will Do for You . . . . . . . . . . . 13
1.3 How to Read This Book . . . . . . . . . . . . . . . . 14
2 Patterns for Cleaner Python 15
2.1 Covering Your A** With Assertions . . . . . . . . . . 16
2.2 Complacent Comma Placement . . . . . . . . . . . . 25
2.3 Context Managers and the with Statement . . . . . . 29
2.4 Underscores, Dunders, and More . . . . . . . . . . . 36
2.5 A Shocking Truth About String Formatting . . . . . . 48
2.6 “The Zen of Python” Easter Egg . . . . . . . . . . . . 56
3 Effective Functions 57
3.1 Python’s Functions Are First-Class . . . . . . . . . . 58
3.2 Lambdas Are Single-Expression Functions . . . . . . 68
3.3 The Power of Decorators . . . . . . . . . . . . . . . 73
3.4 Fun With *args and **kwargs . . . . . . . . . . . . 86
3.5 Function Argument Unpacking . . . . . . . . . . . . 91
3.6 Nothing to Return Here . . . . . . . . . . . . . . . . 94
4 Classes & OOP 97
4.1 Object Comparisons: “is” vs “==” . . . . . . . . . . . 98
4.2 String Conversion (Every Class Needs a __repr__) . 101
4.3 Defining Your Own Exception Classes . . . . . . . . 111
4.4 Cloning Objects for Fun and Profit . . . . . . . . . . 116
4.5 Abstract Base Classes Keep Inheritance in Check . . . 124
4.6 What Namedtuples Are Good For . . . . . . . . . . . 128
4.7 Class vs Instance Variable Pitfalls . . . . . . . . . . . 136
4.8 Instance, Class, and Static Methods Demystified . . . 143
5 Common Data Structures in Python 153
5.1 Dictionaries, Maps, and Hashtables . . . . . . . . . 156
5.2 Array Data Structures . . . . . . . . . . . . . . . . . 163
5.3 Records, Structs, and Data Transfer Objects . . . . . 173
5.4 Sets and Multisets . . . . . . . . . . . . . . . . . . . 185
5.5 Stacks (LIFOs) . . . . . . . . . . . . . . . . . . . . 189
5.6 Queues (FIFOs) . . . . . . . . . . . . . . . . . . . . 195
5.7 Priority Queues . . . . . . . . . . . . . . . . . . . . 201
6 Looping & Iteration 205
6.1 Writing Pythonic Loops . . . . . . . . . . . . . . . . 206
6.2 Comprehending Comprehensions . . . . . . . . . . 210
6.3 List Slicing Tricks and the Sushi Operator . . . . . . 214
6.4 Beautiful Iterators . . . . . . . . . . . . . . . . . . . 218
6.5 Generators Are Simplified Iterators . . . . . . . . . 231
6.6 Generator Expressions . . . . . . . . . . . . . . . . 239
6.7 Iterator Chains . . . . . . . . . . . . . . . . . . . . 246
7 Dictionary Tricks 250
7.1 Dictionary Default Values . . . . . . . . . . . . . . . 251
7.2 Sorting Dictionaries for Fun and Profit . . . . . . . . 255
7.3 Emulating Switch/Case Statements With Dicts . . . . 259
7.4 The Craziest Dict Expression in the West . . . . . . . 264
7.5 So Many Ways to Merge Dictionaries . . . . . . . . . 271
7.6 Dictionary Pretty-Printing . . . . . . . . . . . . . . 274
8 Pythonic Productivity Techniques 277
8.1 Exploring Python Modules and Objects . . . . . . . . 278
8.2 Isolating Project Dependencies With Virtualenv . . . 282
8.3 Peeking Behind the Bytecode Curtain . . . . . . . . . 288
9 Closing Thoughts 293
9.1 Free Weekly Tips for Python Developers . . . . . . . 295
9.2 PythonistaCafe: A Community for Python Developers 296


Bookscreen
e-books shop

What’s a Python Trick?
Python Trick: A short Python code snippet meant as a
teaching tool. A Python Trick either teaches an aspect of
Python with a simple illustration, or it serves as a motivating
example, enabling you to dig deeper and develop an intuitive understanding.

AN INTRODUCTION TO COMPUTER SCIENCE

John M. Zelle


e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 3.00
 Pages
 554 p
 File Size 
 5,838 KB
 File Type
 PDF format
 ISBN
 9781590282755
 Copyright©   
 2017 Franklin, Beedle
 & Associates Incorporated 

Foreword
When the publisher first sent me a draft of this book, I was immediately excited.
Disguised as a Python textbook, it is really an introduction to the fine art of programming,
using Python merely as the preferred medium for beginners. This is
how I have always imagined Python would be most useful in education: not as
the only language, but as a first language, just as in art one might start learning
to draw using a pencil rather than trying to paint in oil right away.
The author mentions in his preface that Python is near-ideal as a first programming
language, without being a "toy language. " As the creator of Python I
don't want to take full credit for this: Python was derived from ABC, a language
designed to teach programming in the early 1980s by Lambert Meertens, Leo
Geurts, and others at CWI (National Research Institute for Mathematics and
Computer Science) in Amsterdam. If I added anything to their work, it was making
Python into a non-toy language, with a broad user base and an extensive
collection of standard and third-party application modules.
I have no formal teaching experience, so I may not be qualified to judge its
educational effectiveness. Still, as a programmer with nearly 30 years experience,
reading through the chapters I am continuously delighted by the book's
clear explanations of difficult concepts. I also like the many good excercises and
questions which both test understanding and encourage thinking about deeper
• ISSUeS.
Reader of this book, congratulations! You will be well rewarded for studying
Python. I promise you'll have fun along the way, and I hope you won't forget
your first language once you have become a proficient software developer.
-Guido van Rossum

Preface
This book is designed to be used as a primary textbook in a college-level first
course in computing. It takes a fairly traditional approach, emphasizing problem
solving, design, and programming as the core skills of computer science. However,
these ideas are illustrated using a non-traditional language, namely Python. In my
teaching experience, I have found that many students have difficulty mastering
the basic concepts of computer science and programming. Part of this difficulty
can be blamed on the complexity of the languages and tools that are most often
used in introductory courses. Consequently, this textbook was written with a
single overarching goal: to introduce fundamental computer science concepts as
simply as possible without being simplistic. Using Python is central to this goal.

Traditional systems languages such as C++, Ada, and Java evolved to solve
problems in large-scale programming, where the primary emphasis is on structure
and discipline. They were not designed to make writing small- or mediumscale
programs easy. The recent rise in popularity of scripting (sometimes called
"agile") languages, such as Python, suggests an alternative approach. Python
is very flexible and makes experimentation easy. Solutions to simple problems
are simply and elegantly expressed. Python provides a great laboratory for the
neophyte programmer.

Python has a number of features that make it a near-perfect choice as a
first programming language. The basic structures are simple, clean, and well
designed, which allows students to focus on the primary skills of algorithmic
thinking and program design without getting bogged down in arcane language
details. Concepts learned in Python carry over directly to subsequent study of
systems languages such as C++ and Java. But Python is not a "toy language."
It is a real-world production language that is freely available for virtually every
programming platform and comes standard with its own easy-to-use integrated
programming environment. The best part is that Python makes learning to program fun again.

Although I use Python as the language, teaching Python is not the main
point of this book. Rather, Python is used to illustrate fundamental principles of
design and programming that apply in any language or computing environment.
In some places I have purposely avoided certain Python features and idioms that
are not generally found in other languages. There are many good books about
Python on the market; this book is intended as an introduction to computing.
Besides using Python, there are other features of this book designed to make it
a gentler introduction to computer science. Some of these features include:

Table of Contents
Foreword, by Guido van Rossum .................... ix
Preface . . . . . . . . . . . . . . . . x
Chapter 1 Computers and Programs
1.1 The Universal Machine 
1.2 Program Power 
1. 3 What Is Computer Science?
1.4 Hardware Basic
1.5 Programming Languages 
1.6 The Magic of Python
1. 7 Inside a Python Program
1.8 Chaos and Computers
1. 9 Chapter S u m mary
1.10 Exercise
Chapter 2 Writing Simple Programs
2.1 The Software Development Process
2. 2 Exam pie Program: T em perature Converter
2.3 Elements of Programs
2.3.1 Names
2.3.2 Expressions
2.4 0 utput Statements
2. 5 Assignment Statements
2. 5 .1 S i m pIe Assign men t
2.5.2 Assigning Input 
2.5.3 Simultaneous Assignment
2. 6 Definite Loops
2.8 Chapter Summary
2.9 Exercises
Chapter 3 Computing with Numbers
3.1 Numeric Data Types
3. 2 Type Conversions and Rounding
3.3 Using the Math Library
3.4 Accumulating Results: Factorials 
3.5 Limitations of Computer Arithmetic
3.6 Chapter Summary
3. 7 Exercises
Chapter 4 Objects and Graphics
4.1 Overview
4. 2 T h e 0 b j ect of 0 b j ects
4.3 Simple Graphics Programming
4.4 Using Graphical Objects
4.5 Graphing Future Value
4.6 Choosing Coordinates
4. 7 Interactive Graphics 
4.7.1 Getting Mouse Clicks
4. 7.2 Handling Textual Input
4.8 Graphics Module Reference
4.8.1 Graph Win Objects
4. 8. 2 G ra ph i cs 0 b j ects
4.8.3 Entry Objects
4.8.4 Displaying I mages
4.8.5 Generating Colors
4.8.6 Controlling Display Updates (Advanced)
4. 9 Chapter Sum mary 
4.10 Exercises
Chapter 5 Sequences: Strings, Lists, and Files
5.2 Si m pie String Processing
5.3 Lists as Sequences
5.4 String Representation and Message Encoding 
5.4.1 String Representation
5.4.2 Programming an Encoder
5.5 String Methods
5.5.1 Programming a Decoder
5.5.2 More String Methods
5.6 Lists Have Methods. Too 
5. 7 From Encoding to Encryption
5.8 Input/Output as String Manipulation 
5. 8.1 Exam pie Application: Date Conversion
5. 8. 2 String Formatting
5.8.3 Better Change Counter
5. 9 File Processing 
5.9.1 Multi-line Strings
5.9.2 File Processing
5.9.3 Example Program: Batch Usernames
5.9.4 File Dialogs (Optional)
5.10 Chapter Summary 
5.11 Exercises 
Chapter 6 Defining Functions
6.1 The Function of Functions
6.2 Functions, Informally 
6.3 Future Value with a Function
6.4 Functions and Para meters: The Exciting Deta i Is
6.5 Functions That Return Values
6.6 Functions that Modify Para meters 
6.7 Functions and Program Structure
6.8 Chapter Summary
6.9 Exercises
Chapter 7 Decision Structures
7.1 Sim pie Decisions
7.1.1 Example: Temperature Warnings 
7.1.2 Forming Simple Conditions
7 .1.3 Example: Condition a I Program Execution
7. 2 Two-Way Decisions
7.3 Multi-Way Decisions
7.4 Exception Handling 
7. 5 Study in Design: Max of Three 
7.5.1 Strategy 1: Compare Each to All
7.5. 2 Strategy 2: Decision Tree
7 .5.3 Strategy 3: Sequential Processing
7 .5.4 Strategy 4: Use Python
7 .5.5 Some Lessons
7.6 Chapter Summary
7. 7 Exercises
Chapter 8 Loop Structures and Booleans
8.1 For Loops: A Quick Review
8.2 Indefinite Loops
8. 3 Common Loop Patterns
8. 3.1 Interactive Loops
8.3.2 Sentinel Loops
8.3.3 File Loops
8.3.4 Nested Loops
8.4 Computing with Boo leans
8.4.1 Boolean Operators 
8.4.2 Boolean Algebra
8. 5 Other Common Structures
8.5.1 Post-test Loop 
8.5.2 Loop and a Half 
8.5.3 Boolean Expressions as Decisions
8.6 Example: A Simple Event Loop 
8. 7 Chapter Summary
8. 8 Exercises
Chapter 9 Simulation and Design
9 .1 S i m u I at i n g Ra cq u et ba II
9.1.1 A Simulation Problem
9 .1. 2 Ana lysis and Specification
9. 2 Pseudo-random Numbers 
9.3 Top-Down Design
9. 3.1 Top-Level Design 
9. 3. 2 Separation of Concerns
9.3.3 Second-Level Design 
9.3.4 Designing simNGames
9.3.5 Third-Level Design
9.3.6 Finishing Up
9.3. 7 Summary of the Design Process
9.4 Bottom-Up Implementation
9.4.1 Unit Testing
9.4.2 Simulation Results
9. 5 Other Design Techniques 
9.5.1 Prototyping and Spiral Development 
9.5.2 The Art of Design
9.6 Chapter Summary
9. 7 Exercises
Chapter 10 Defining Classes
10.1 Quick Review of Objects
10.2 Example Program: Cannonball
10.2.1 Program Specification
10.2.2 Designing the Program
10.2.3 Mod ularizing the Program
10.3 Defining New Classes
10.3.1 Example: Multi-sided Dice
10.3.2 Example: The Projectile Class
10.4 Data Processing with Class
10.5 0 bjects and Encapsulation
10.5.1 Encapsulating Useful Abstractions
10.5.2 Putting Classes in Modules
10.5.3 Module Documentation
10.5.4 Working with Multiple Modules
10.6 Widgets 
10.6.1 Example Program: Dice Roller
10.6.2 Building Buttons 
10.6.3 Building Dice
10.6.4 The Main Program
10. 7 Anima ted Can non ba II
10.7.1 Drawing the Animation Window
10.7 .2 Creating a Shot Tracker
10.7.3 Creating an Input Dialog
10.7.4 The Main Event Loop
10. 8 Chapter S u m mary
10.9 Exercises
Chapter 11 Data Collections
11.1 Exam pie Problem: S i m pie Statistics
11.2 Applying Lists
11.2.1 Lists and Arrays
11.2. 2 List 0 perations
11.2.3 Statistics with Lists
11.3 Lists of Records
11.4 Designing with Lists and Classes
11.5 Case Study: Python Ca leu Ia tor
11.5.1 A Calculator as an Object
11.5. 2 Constructing the Interface
11.5.3 Processing Buttons 
11.6 Case Study: Better Can non ba II Animation
11.6 .1 Creating a Launcher
11.6.2 Tracking Multiple Shots 
11.7 Non-seq uenti a I Collections
11.7 .1 Dictionary Basics
11.7. 2 Dictionary 0 perations
11.7.3 Example Program: Word Frequency
11. 8 Chapter S u m mary
11.9 Exercises
Chapter 12 Object-Oriented Design
12.1 The Process of OOD
12.2 Case Study: Racq uetba II Simulation
12.2.1 Candidate Objects and Methods
12.2.2 Implementing SimStat
12.2.3 Implementing RBaiiGame 
12.2.4 Implementing Player
12.2.5 The Complete Program
12.3 Case Study: Dice Poker
12.3.1 Program Specification
12.3.2 Identifying Candidate Objects
12.3.3Implementing the Model
12.3.4 A Text-Based U I
12.3.5 Developing a G U I
12.4 00 Concepts
12.4.1 Encapsulation
12.4.2 Polymorph ism
12.4.3 Inheritance
12. 5 Chapter S u m mary
12.6 Exercises
Chapter 13 Algorithm Design and Recursion
13.1 Searching
13.1.1 A Si m pie Searching Problem
13.1.2 Strategy 1: Linear Search
13.1.3 Strategy 2: Binary Search
13.1.4 Com paring Algorithms
13.2 Recursive Problem Solving
13.2.1 Recursive Definitions 
13.2.2 Recursive Functions
13.2.3 Example: String Reversal
13.2.4 Example: Anagrams
13.2.5 Example: Fast Exponentiation
13.2.6 Example: Binary Search 
13.2. 7 Recursion vs. Iteration
13.3 Sorting Algorithms
13.3.1 Naive Sorting: Selection Sort
13.3.2 Divide and Conquer: Merge Sort
13 . 3 . 3 Com pa r i n g Sorts
13.4 Hard Problems
13.4.1 Tower of Hanoi
13.4.2 The Halting Problem
13.4.3 Conclusion
13.5 Chapter Summary
13.6 Exercises 
Appendix A Python Quick Reference
Appendix C Glossary
Index


Bookscreen
e-books shop

Introduction
• Extensive use of computer graphics. Students love working on
programs that include graphics. This book presents a simple-to-use graphics
package (provided as a Python module) that allows students both to
learn the principles of computer graphics and to practice object-oriented
concepts without the complexity inherent in a full-blown graphics library
and event-driven programming.
• Interesting examples. The book is packed with complete programming
examples to solve real problems.
• Readable prose. The narrative style of the book introduces key computer
science concepts in a natural way as an outgrowth of a developing discussion.
I have tried to avoid random facts or tangentially related sidebars.
• Flexible spiral coverage. Since the goal of the book is to present concepts
simply, each chapter is organized so that students are introduced to
new ideas in a gradual way, giving them time to assimilate an increasing
level of detail as they progress. Ideas that take more time to master are
introduced in early chapters and reinforced in later chapters.
• Just-in-time object coverage. The proper place for the introduction of
object-oriented techniques is an ongoing controversy in computer science
education. This book is neither strictly "objects early'' nor "objects late,"
but gradually introduces object concepts after a brief initial grounding
in the basics of imperative programming. Students learn multiple design
techniques, including top-down (functional decomposition) , spiral (prototyping)
, and object-oriented methods. Additionally, the textbook material
is flexible enough to accommodate other approaches.
• Extensive end-of-chapter problems. Exercises at the end of every
chapter provide ample opportunity for students to reinforce their mastery
of the chapter material and to practice new programming skills.

Over 80 object-oriented recipes to help you create mind-blowing GUIs in Python

Burkhard A. Meier


e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 2.50
 Pages
 351 p
 File Size 
 9,239 KB
 File Type
 PDF format
 ISBN
 978-1-78528-375-8
 Copyright©   
 2015 Packt Publishing 

About the Author
Burkhard A. Meier has more than 15 years of professional experience working in the
software industry as a software tester and developer, specializing in software test automation
development, execution, and analysis. He has a very strong background in SQL relational
database administration, the development of stored procedures, and debugging code.
While experienced in Visual Studio .NET C#, Visual Test, TestComplete, and other testing
languages (such as C/C++), the main focus of the author over the past two years has been
developing test automation written in Python 3 to test the leading edge of FLIR ONE infrared
cameras for iPhone and Android smart phones as well as handheld tablets.

Being highly appreciative of art, beauty, and programming, the author developed GUIs in C# and
Python to streamline everyday test automation tasks, enabling these automated tests to run
unattended for weeks, collecting very useful data to be analyzed and automatically plotted into
graphs and e-mailed to upper management upon completion of nightly automated test runs.
His previous jobs include working as a senior test automation engineer and designer for
InfoGenesis (now Agilysys), QAD, InTouch Health, and presently, FLIR Systems.
You can get in touch with him through his LinkedIn account, 

About the Reviewers
Joy Bindroo holds a bachelor's degree in computer science and engineering. He is currently
pursuing his post-graduate studies in the field of information management. He is a creative
person and enjoys working on Linux platform and other open source technologies. He
enjoys writing about Python and sharing his ideas and skills on his website, http://www.joybindroo.com/
He likes to sketch, write poems, listen to music, and have fun with his
friends in his free time.

Peter Bouda works as a senior web developer for MAJ Digital and is a specialist in
full stack JavaScript applications based on LoopBack and AngularJS. He develops Python
GUIs for companies and research projects since 2003 and wrote a German book, PyQt und
PySide – GUI- und Anwendungsentwicklung mit Python und Qt, on Python GUI development,
which was published in 2012. Currently, he is getting crazy with embedded and open
hardware platforms and is working on a modular game console based on open hardware.

Joseph Rex is a full stack developer with a background in computer security. He has worked
on Python GUI products and some CLI programs to experiment with information security. He
came out of security to web development and developed a passion for rails and JavaScript MVC
frameworks after working on several projects using jQuery. He has been in the web industry
for 3 years, building web applications and mobile apps. He has also written articles on security
for InfoSec Institute and has written some scripts to back them up. He has to his credit several
personal experimental projects written in Python.

Preface
In this book, we will explore the beautiful world of graphical user interfaces (GUIs) 
using the Python programming language.
Along the way, we will talk to networks, queues,
 the OpenGL graphical library, and many more technologies.
This is a programming cookbook. Every chapter is self-contained 
and explains a certain programming solution.
We will start very simply, yet throughout this book 
we will build a working program written in Python 3.
We will also apply some design patterns and use best practices throughout this book.
The book assumes that the reader has some basic experience using the Python
programming language, but that is not really required to use this book.
If you are an experienced programmer in any programming language, you will have a fun

time extending your skills to programming GUIs using Python!

Are you ready?

Let's start on our journey…

What you need for this book
All required software for this book is available online and is free of charge. This starts with
Python 3 itself, and then extends to Python's add-on modules. In order to download any
required software, you will need a working Internet connection.

Table of Contents
Preface v
Chapter 1: Creating the GUI Form and Adding Widgets 1
Introduction 1
Creating our first Python GUI 2
Preventing the GUI from being resized 4
Adding a label to the GUI form 6
Creating buttons and changing their text property 7
Text box widgets 9
Setting the focus to a widget and disabling widgets 11
Combo box widgets 12
Creating a check button with different initial states 14
Using radio button widgets 16
Using scrolled text widgets 18
Adding several widgets in a loop 20
Chapter 2: Layout Management 23
Introduction 23
Arranging several labels within a label frame widget 24
Using padding to add space around widgets 26
How widgets dynamically expand the GUI 28
Aligning the GUI widgets by embedding frames within frames 32
Creating menu bars 36
Creating tabbed widgets 41
Using the grid layout manager 46
Chapter 3: Look and Feel Customization 49
Introduction 49
Creating message boxes – information, warning, and error 50
How to create independent message boxes 53
How to create the title of a tkinter window form 56
Changing the icon of the main root window 57
Using a spin box control 58
Relief, sunken, and raised appearance of widgets 61
Creating tooltips using Python 63
How to use the canvas widget 67
Chapter 4: Data and Classes 69
Introduction 69
How to use StringVar() 69
How to get data from a widget 73
Using module-level global variables 75
How coding in classes can improve the GUI 79
Writing callback functions 85
Creating reusable GUI components 86
Chapter 5: Matplotlib Charts 91
Introduction 91
Creating beautiful charts using Matplotlib 92
Matplotlib – downloading modules using pip 94
Matplotlib – downloading modules with whl extensions 98
Creating our first chart 100
Placing labels on charts 102
How to give the chart a legend 106
Scaling charts 109
Adjusting the scale of charts dynamically 112
Chapter 6: Threads and Networking 117
Introduction 117
How to create multiple threads 118
Starting a thread 121
Stopping a thread 125
How to use queues 128
Passing queues among different modules 133
Using dialog widgets to copy files to your network 136
Using TCP/IP to communicate via networks 145
Using URLOpen to read data from websites 147
Chapter 7: Storing Data in Our MySQL Database via Our GUI 153
Introduction 153
Connecting to a MySQL database from Python 154
Configuring the MySQL connection 157
Designing the Python GUI database 161
Using the SQL INSERT command 168
Using the SQL UPDATE command 172
Using the SQL DELETE command 177
Storing and retrieving data from our MySQL database 181
Chapter 8: Internationalization and Testing 187
Introduction 187
Displaying widget text in different languages 188
Changing the entire GUI language all at once 191
Localizing the GUI 196
Preparing the GUI for internationalization 201
How to design a GUI in an agile fashion 204
Do we need to test the GUI code? 208
Setting debug watches 212
Configuring different debug output levels 216
Creating self-testing code using
Python's __main__ section 220
Creating robust GUIs using unit tests 224
How to write unit tests using the Eclipse PyDev IDE 229
Chapter 9: Extending Our GUI with the wxPython Library 235
Introduction 235
How to install the wxPython library 236
How to create our GUI in wxPython 239
Quickly adding controls using wxPython 244
Trying to embed a main wxPython app in a main tkinter app 251
Trying to embed our tkinter GUI code into wxPython 253
How to use Python to control two different GUI frameworks 256
How to communicate between the two connected GUIs 260
Chapter 10: Creating Amazing 3D GUIs with PyOpenGL and PyGLet 265
Introduction 265
PyOpenGL transforms our GUI 266
Our GUI in 3D! 270
Using bitmaps to make our GUI pretty 275
PyGLet transforms our GUI more easily than PyOpenGL 279
Our GUI in amazing colors 283
Creating a slideshow using tkinter 286
Chapter 11: Best Practices 291
Introduction 291
Avoiding spaghetti code 291
Using __init__ to connect modules 298
Mixing fall-down and OOP coding 305
Using a code naming convention 310
When not to use OOP 314
How to use design patterns successfully 317
Avoiding complexity 320
Index 327


Bookscreen
e-books shop

Who this book is forI
This book is for programmers who wish to create a graphical user interface (GUI). You might
be surprised by what we can achieve by creating beautiful, functional, and powerful GUIs
using the Python programming language. Python is a wonderful, intuitive programming
language, and is very easy to learn.

I like to invite you to start on this journey now. It will be a lot of fun!

Powerful Object-Oriented Programming

by Mark Lutz


e-books shop
e-books shop
Purchase Now !
Just with Paypal



Book Details
 Price
 5.00
 Pages
 1628 p
 File Size 
 30,142 KB
 File Type
 PDF format
 ISBN
 978-0-596-15810-1 
 Copyright©   
 2011 Mark Lutz   

Preface
“And Now for Something Completely Different…”
This book explores ways to apply the Python programming language in common application
domains and realistically scaled tasks. It’s about what you can do with the
language once you’ve mastered its fundamentals.
This book assumes you are relatively new to each of the application domains it covers—
GUIs, the Internet, databases, systems programming, and so on—and presents each
from the ground up, in tutorial fashion. Along the way, it focuses on commonly used
tools and libraries, rather than language fundamentals. The net result is a resource that
provides readers with an in-depth understanding of Python’s roles in practical, realworld
programming work.
As a subtheme, this book also explores Python’s relevance as a software development
tool—a role that many would classify as well beyond those typically associated with
“scripting.” In fact, many of this book’s examples are scaled specifically for this purpose;
among these, we’ll incrementally develop email clients that top out at thousands
of lines of code. Programming at this full scale will always be challenging work, but
we’ll find that it’s also substantially quicker and easier when done with Python.
This Fourth Edition has been updated to present the language, libraries, and practice
of Python 3.X. Specifically, its examples use Python 3.1—the most recent version of
Python at the time of writing—and its major examples were tested successfully under
the third alpha release of Python 3.2 just prior to publication, but they reflect the version
of the language common to the entire 3.X line. This edition has also been reorganized
in ways that both streamline some of its former material and allow for coverage of newly
emerged tools and topics.
Because this edition’s readership will include both newcomers as well as prior edition
veterans, I want to use this Preface to expand on this book’s purpose and scope before
we jump into code.

What This Book Is Not
Because of the scopes carved out by the related books I just mentioned, this book’s
scope follows two explicit constraints:
• It does not cover Python language fundamentals
• It is not intended as a language reference
The former of these constraints reflects the fact that core language topics are the exclusive
domain of Learning Python, and I encourage you to consult that book before
tackling this one if you are completely new to the Python language, as its topics are
assumed here. Some language techniques are shown by example in this book too, of
course, and the larger examples here illustrate how core concepts come together into
realistic programs. OOP, for example, is often best sampled in the context of the larger
programs we’ll write here. Officially, though, this book assumes you already know
enough Python fundamentals to understand its example code. Our focus here is mostly
on libraries and tools; please see other resources if the basic code we’ll use in that role is unclear.

The latter of the two constraints listed above reflects what has been a common misconception
about this book over the years (indeed, this book might have been better
titled Applying Python had we been more clairvoyant in 1995). I want to make this as
clear as I can: this is not a reference book. It is a tutorial. Although you can hunt for
some details using the index and table of contents, this book is not designed for that
purpose. Instead, Python Pocket Reference provides the sort of quick reference to details
that you’ll find useful once you start writing nontrivial code on your own. There are
other reference-focused resources available, including other books and Python’s own
reference manuals set. Here, the goal is a gradual tutorial that teaches you how to apply
Python to common tasks but does not document minute details exhaustively.

About This Fourth Edition
If this is the first edition of this book you’ve seen, you’re probably less interested in
recent changes, and you should feel free to skip ahead past this section. For readers of
prior editions, though, this Fourth Edition of this book has changed in three important
ways:
• It’s been updated to cover Python 3.X (only).
• It’s been slimmed down to sharpen its focus and make room for new topics.
• It’s been updated for newly emerged topics and tools in the Python world.
The first of these is probably the most significant—this edition employs the Python 3.X
language, its version of the standard library, and the common practice of its users. To
better explain how this and the other two changes take shape in this edition, though,
I need to fill in a few more details.

Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Part I. The Beginning
1. A Sneak Preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
“Programming Python: The Short Story” 3
The Task 4
Step 1: Representing Records 4
Using Lists 4
Using Dictionaries 9
Step 2: Storing Records Persistently 14
Using Formatted Files 14
Using Pickle Files 19
Using Per-Record Pickle Files 22
Using Shelves 23
Step 3: Stepping Up to OOP 26
Using Classes 27
Adding Behavior 29
Adding Inheritance 29
Refactoring Code 31
Adding Persistence 34
Other Database Options 36
Step 4: Adding Console Interaction 37
A Console Shelve Interface 37
Step 5: Adding a GUI 40
GUI Basics 40
Using OOP for GUIs 42
Getting Input from a User 44
A GUI Shelve Interface 46
Step 6: Adding a Web Interface 52
CGI Basics 52
Running a Web Server 55
Using Query Strings and urllib 57
Formatting Reply Text 59
A Web-Based Shelve Interface 60
The End of the Demo 69
Part II. System Programming
2. System Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
“The os.path to Knowledge” 73
Why Python Here? 73
The Next Five Chapters 74
System Scripting Overview 75
Python System Modules 76
Module Documentation Sources 77
Paging Documentation Strings 78
A Custom Paging Script 79
String Method Basics 80
Other String Concepts in Python 3.X: Unicode and bytes 82
File Operation Basics 83
Using Programs in Two Ways 84
Python Library Manuals 85
Commercially Published References 86
Introducing the sys Module 86
Platforms and Versions 86
The Module Search Path 87
The Loaded Modules Table 88
Exception Details 89
Other sys Module Exports 90
Introducing the os Module 90
Tools in the os Module 90
Administrative Tools 91
Portability Constants 92
Common os.path Tools 92
Running Shell Commands from Scripts 94
Other os Module Exports 100
3. Script Execution Context . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
“I’d Like to Have an Argument, Please” 103
Current Working Directory 104
CWD, Files, and Import Paths 104
CWD and Command Lines 106
Command-Line Arguments 106
Parsing Command-Line Arguments 107
Shell Environment Variables 109
Fetching Shell Variables 110
Changing Shell Variables 111
Shell Variable Fine Points: Parents, putenv, and getenv 112
Standard Streams 113
Redirecting Streams to Files and Programs 114
Redirected Streams and User Interaction 119
Redirecting Streams to Python Objects 123
The io.StringIO and io.BytesIO Utility Classes 126
Capturing the stderr Stream 127
Redirection Syntax in Print Calls 127
Other Redirection Options: os.popen and subprocess Revisited 128
4. File and Directory Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
“Erase Your Hard Drive in Five Easy Steps!” 135
File Tools 135
The File Object Model in Python 3.X 136
Using Built-in File Objects 137
Binary and Text Files 146
Lower-Level File Tools in the os Module 155
File Scanners 160
Directory Tools 163
Walking One Directory 164
Walking Directory Trees 168
Handling Unicode Filenames in 3.X: listdir, walk, glob 172
5. Parallel System Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
“Telling the Monkeys What to Do” 177
Forking Processes 179
The fork/exec Combination 182
Threads 186
The _thread Module 189
The threading Module 199
The queue Module 204
Preview: GUIs and Threads 208
More on the Global Interpreter Lock 211
Program Exits 213
sys Module Exits 214
os Module Exits 215
Shell Command Exit Status Codes 216
Process Exit Status and Shared State 219
Thread Exits and Shared State 220
Interprocess Communication 222
Anonymous Pipes 224
Named Pipes (Fifos) 234
Sockets: A First Look 236
Signals 240
The multiprocessing Module 243
Why multiprocessing? 243
The Basics: Processes and Locks 245
IPC Tools: Pipes, Shared Memory, and Queues 248
Starting Independent Programs 254
And Much More 256
Why multiprocessing? The Conclusion 257
Other Ways to Start Programs 258
The os.spawn Calls 258
The os.startfile call on Windows 261
A Portable Program-Launch Framework 263
Other System Tools Coverage 268
6. Complete System Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
“The Greps of Wrath” 271
A Quick Game of “Find the Biggest Python File” 272
Scanning the Standard Library Directory 272
Scanning the Standard Library Tree 273
Scanning the Module Search Path 274
Scanning the Entire Machine 276
Printing Unicode Filenames 279
Splitting and Joining Files 282
Splitting Files Portably 283
Joining Files Portably 286
Usage Variations 289
Generating Redirection Web Pages 292
Page Template File 293
Page Generator Script 294
A Regression Test Script 297
Running the Test Driver 299
Copying Directory Trees 304
Comparing Directory Trees 308
Finding Directory Differences 309
Finding Tree Differences 311
Running the Script 314
Verifying Backups 316
Reporting Differences and Other Ideas 317
Searching Directory Trees 319
Greps and Globs and Finds 320
Rolling Your Own find Module 321
Cleaning Up Bytecode Files 324
A Python Tree Searcher 327
Visitor: Walking Directories “++” 330
Editing Files in Directory Trees (Visitor) 334
Global Replacements in Directory Trees (Visitor) 336
Counting Source Code Lines (Visitor) 338
Recoding Copies with Classes (Visitor) 339
Other Visitor Examples (External) 341
Playing Media Files 343
The Python webbrowser Module 347
The Python mimetypes Module 348
Running the Script 350
Automated Program Launchers (External) 351
Part III. GUI Programming
7. Graphical User Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
“Here’s Looking at You, Kid” 355
GUI Programming Topics 355
Running the Examples 357
Python GUI Development Options 358
tkinter Overview 363
tkinter Pragmatics 363
tkinter Documentation 364
tkinter Extensions 364
tkinter Structure 366
Climbing the GUI Learning Curve 368
“Hello World” in Four Lines (or Less) 368
tkinter Coding Basics 369
Making Widgets 370
Geometry Managers 370
Running GUI Programs 371
tkinter Coding Alternatives 372
Widget Resizing Basics 373
Configuring Widget Options and Window Titles 375
One More for Old Times’ Sake 376
Packing Widgets Without Saving Them 377
Adding Buttons and Callbacks 379
Widget Resizing Revisited: Expansion 380
Adding User-Defined Callback Handlers 382
Lambda Callback Handlers 383
Deferring Calls with Lambdas and Object References 384
Callback Scope Issues 385
Bound Method Callback Handlers 391
Callable Class Object Callback Handlers 392
Other tkinter Callback Protocols 393
Binding Events 394
Adding Multiple Widgets 395
Widget Resizing Revisited: Clipping 396
Attaching Widgets to Frames 397
Layout: Packing Order and Side Attachments 397
The Packer’s Expand and Fill Revisited 398
Using Anchor to Position Instead of Stretch 399
Customizing Widgets with Classes 400
Standardizing Behavior and Appearance 401
Reusable GUI Components with Classes 403
Attaching Class Components 405
Extending Class Components 407
Standalone Container Classes 408
The End of the Tutorial 410
Python/tkinter for Tcl/Tk Converts 412
8. A tkinter Tour, Part 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
“Widgets and Gadgets and GUIs, Oh My!” 415
This Chapter’s Topics 415
Configuring Widget Appearance 416
Top-Level Windows 419
Toplevel and Tk Widgets 421
Top-Level Window Protocols 422
Dialogs 426
Standard (Common) Dialogs 426
The Old-Style Dialog Module 438
Custom Dialogs 439
Binding Events 443
Other bind Events 447
Message and Entry 448
Message 448
Entry 449
Laying Out Input Forms 451
tkinter “Variables” and Form Layout Alternatives 454
Checkbutton, Radiobutton, and Scale 457
Checkbuttons 457
Radio Buttons 462
Scales (Sliders) 467
Running GUI Code Three Ways 471
Attaching Frames 471
Independent Windows 476
Running Programs 478
Images 484
Fun with Buttons and Pictures 487
Viewing and Processing Images with PIL 491
PIL Basics 491
Displaying Other Image Types with PIL 493
Creating Image Thumbnails with PIL 496
9. A tkinter Tour, Part 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
“On Today’s Menu: Spam, Spam, and Spam” 507
Menus 507
Top-Level Window Menus 508
Frame- and Menubutton-Based Menus 512
Windows with Both Menus and Toolbars 517
Listboxes and Scrollbars 522
Programming Listboxes 524
Programming Scroll Bars 525
Packing Scroll Bars 526
Text 528
Programming the Text Widget 530
Adding Text-Editing Operations 533
Unicode and the Text Widget 538
Advanced Text and Tag Operations 548
Canvas 550
Basic Canvas Operations 550
Programming the Canvas Widget 551
Scrolling Canvases 554
Scrollable Canvases and Image Thumbnails 557
Using Canvas Events 560
Grids 564
Why Grids? 564
Grid Basics: Input Forms Revisited 565
Comparing grid and pack 566
Combining grid and pack 568
Making Gridded Widgets Expandable 570
Laying Out Larger Tables with grid 574
Time Tools, Threads, and Animation 582
Using Threads with tkinter GUIs 584
Using the after Method 585
Simple Animation Techniques 588
Other Animation Topics 593
The End of the Tour 595
Other Widgets and Options 595
10. GUI Coding Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
“Building a Better Mousetrap” 597
GuiMixin: Common Tool Mixin Classes 598
Widget Builder Functions 598
Mixin Utility Classes 599
GuiMaker: Automating Menus and Toolbars 603
Subclass Protocols 607
GuiMaker Classes 608
GuiMaker Self-Test 608
BigGui: A Client Demo Program 609
ShellGui: GUIs for Command-Line Tools 613
A Generic Shell-Tools Display 613
Application-Specific Tool Set Classes 615
Adding GUI Frontends to Command Lines 617
GuiStreams: Redirecting Streams to Widgets 623
Using Redirection for the Packing Scripts 627
Reloading Callback Handlers Dynamically 628
Wrapping Up Top-Level Window Interfaces 630
GUIs, Threads, and Queues 635
Placing Data on Queues 636
Placing Callbacks on Queues 640
More Ways to Add GUIs to Non-GUI Code 646
Popping Up GUI Windows on Demand 647
Adding a GUI As a Separate Program: Sockets (A Second Look) 649
Adding a GUI As a Separate Program: Command Pipes 654
The PyDemos and PyGadgets Launchers 662
PyDemos Launcher Bar (Mostly External) 662
PyGadgets Launcher Bar 667
11. Complete GUI Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
“Python, Open Source, and Camaros” 671
Examples in Other Chapters 672
This Chapter’s Strategy 673
PyEdit: A Text Editor Program/Object 674
Running PyEdit 675
PyEdit Changes in Version 2.0 (Third Edition) 682
PyEdit Changes in Version 2.1 (Fourth Edition) 684
PyEdit Source Code 693
PyPhoto: An Image Viewer and Resizer 716
Running PyPhoto 717
PyPhoto Source Code 719
PyView: An Image and Notes Slideshow 727
Running PyView 727
PyView Source Code 732
PyDraw: Painting and Moving Graphics 738
Running PyDraw 738
PyDraw Source Code 738
PyClock: An Analog/Digital Clock Widget 747
A Quick Geometry Lesson 747
Running PyClock 751
PyClock Source Code 754
PyToe: A Tic-Tac-Toe Game Widget 762
Running PyToe 762
PyToe Source Code (External) 763
Where to Go from Here 766
Part IV. Internet Programming
12. Network Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
“Tune In, Log On, and Drop Out” 771
Internet Scripting Topics 772
Running Examples in This Part of the Book 775
Python Internet Development Options 777
Plumbing the Internet 780
The Socket Layer 781
The Protocol Layer 782
Python’s Internet Library Modules 785
Socket Programming 787
Socket Basics 788
Running Socket Programs Locally 794
Running Socket Programs Remotely 795
Spawning Clients in Parallel 798
Talking to Reserved Ports 801
Handling Multiple Clients 802
Forking Servers 803
Threading Servers 815
Standard Library Server Classes 818
Multiplexing Servers with select 820
Summary: Choosing a Server Scheme 826
Making Sockets Look Like Files and Streams 827
A Stream Redirection Utility 828
A Simple Python File Server 840
Running the File Server and Clients 842
Adding a User-Interface Frontend 843
13. Client-Side Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
“Socket to Me!” 853
FTP: Transferring Files over the Net 854
Transferring Files with ftplib 854
Using urllib to Download Files 857
FTP get and put Utilities 860
Adding a User Interface 867
Transferring Directories with ftplib 874
Downloading Site Directories 874
Uploading Site Directories 880
Refactoring Uploads and Downloads for Reuse 884
Transferring Directory Trees with ftplib 892
Uploading Local Trees 893
Deleting Remote Trees 895
Downloading Remote Trees 899
Processing Internet Email 899
Unicode in Python 3.X and Email Tools 900
POP: Fetching Email 901
Mail Configuration Module 902
POP Mail Reader Script 905
Fetching Messages 906
Fetching Email at the Interactive Prompt 909
SMTP: Sending Email 910
SMTP Mail Sender Script 911
Sending Messages 913
Sending Email at the Interactive Prompt 919
email: Parsing and Composing Mail Content 921
Message Objects 922
Basic email Package Interfaces in Action 924
Unicode, Internationalization, and the Python 3.1 email Package 926
A Console-Based Email Client 947
Running the pymail Console Client 952
The mailtools Utility Package 956
Initialization File 957
MailTool Class 958
MailSender Class 959
MailFetcher Class 967
MailParser Class 976
Self-Test Script 983
Updating the pymail Console Client 986
NNTP: Accessing Newsgroups 991
HTTP: Accessing Websites 994
The urllib Package Revisited 997
Other urllib Interfaces 999
Other Client-Side Scripting Options 1002
14. The PyMailGUI Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1005
“Use the Source, Luke” 1005
Source Code Modules and Size 1006
Why PyMailGUI? 1008
Running PyMailGUI 1010
Presentation Strategy 1010
Major PyMailGUI Changes 1011
New in Version 2.1 and 2.0 (Third Edition) 1011
New in Version 3.0 (Fourth Edition) 1012
A PyMailGUI Demo 1019
Getting Started 1020
Loading Mail 1025
Threading Model 1027
Load Server Interface 1030
Offline Processing with Save and Open 1031
Sending Email and Attachments 1033
Viewing Email and Attachments 1037
Email Replies and Forwards and Recipient Options 1043
Deleting Email 1049
POP Message Numbers and Synchronization 1051
Handling HTML Content in Email 1053
Mail Content Internationalization Support 1055
Alternative Configurations and Accounts 1059
Multiple Windows and Status Messages 1060
PyMailGUI Implementation 1062
PyMailGUI: The Main Module 1063
SharedNames: Program-Wide Globals 1066
ListWindows: Message List Windows 1067
ViewWindows: Message View Windows 1085
messagecache: Message Cache Manager 1095
popuputil: General-Purpose GUI Pop Ups 1098
wraplines: Line Split Tools 1100
html2text: Extracting Text from HTML (Prototype, Preview) 1102
mailconfig: User Configurations 1105
textConfig: Customizing Pop-Up PyEdit Windows 1110
PyMailGUIHelp: User Help Text and Display 1111
altconfigs: Configuring for Multiple Accounts 1114
Ideas for Improvement 1116
15. Server-Side Scripting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1125
“Oh, What a Tangled Web We Weave” 1125
What’s a Server-Side CGI Script? 1126
The Script Behind the Curtain 1126
Writing CGI Scripts in Python 1128
Running Server-Side Examples 1130
Web Server Options 1130
Running a Local Web Server 1131
The Server-Side Examples Root Page 1133
Viewing Server-Side Examples and Output 1134
Climbing the CGI Learning Curve 1135
A First Web Page 1135
A First CGI Script 1141
Adding Pictures and Generating Tables 1146
Adding User Interaction 1149
Using Tables to Lay Out Forms 1157
Adding Common Input Devices 1163
Changing Input Layouts 1166
Passing Parameters in Hardcoded URLs 1170
Passing Parameters in Hidden Form Fields 1172
Saving State Information in CGI Scripts 1174
URL Query Parameters 1176
Hidden Form Input Fields 1176
HTTP “Cookies” 1177
Server-Side Databases 1181
Extensions to the CGI Model 1182
Combining Techniques 1183
The Hello World Selector 1183
Checking for Missing and Invalid Inputs 1190
Refactoring Code for Maintainability 1192
Step 1: Sharing Objects Between Pages—A New Input Form 1193
Step 2: A Reusable Form Mock-Up Utility 1196
Step 3: Putting It All Together—A New Reply Script 1199
More on HTML and URL Escapes 1201
URL Escape Code Conventions 1202
Python HTML and URL Escape Tools 1203
Escaping HTML Code 1203
Escaping URLs 1204
Escaping URLs Embedded in HTML Code 1205
Transferring Files to Clients and Servers 1209
Displaying Arbitrary Server Files on the Client 1211
Uploading Client Files to the Server 1218
More Than One Way to Push Bits over the Net 1227
16. The PyMailCGI Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1229
“Things to Do When Visiting Chicago” 1229
The PyMailCGI Website 1230
Implementation Overview 1230
New in This Fourth Edition (Version 3.0) 1233
New in the Prior Edition (Version 2.0) 1235
Presentation Overview 1236
Running This Chapter’s Examples 1237
The Root Page 1239
Configuring PyMailCGI 1240
Sending Mail by SMTP 1241
The Message Composition Page 1242
The Send Mail Script 1242
Error Pages 1246
Common Look-and-Feel 1246
Using the Send Mail Script Outside a Browser 1247
Reading POP Email 1249
The POP Password Page 1250
The Mail Selection List Page 1251
Passing State Information in URL Link Parameters 1254
Security Protocols 1257
The Message View Page 1259
Passing State Information in HTML Hidden Input Fields 1262
Escaping Mail Text and Passwords in HTML 1264
Processing Fetched Mail 1266
Reply and Forward 1267
Delete 1268
Deletions and POP Message Numbers 1272
Utility Modules 1276
External Components and Configuration 1276
POP Mail Interface 1277
POP Password Encryption 1278
Common Utilities Module 1286
Web Scripting Trade-Offs 1291
PyMailCGI Versus PyMailGUI 1292
The Web Versus the Desktop 1293
Other Approaches 1296
Part V. Tools and Techniques
17. Databases and Persistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1303
“Give Me an Order of Persistence, but Hold the Pickles” 1303
Persistence Options in Python 1303
DBM Files 1305
Using DBM Files 1305
DBM Details: Files, Portability, and Close 1308
Pickled Objects 1309
Using Object Pickling 1310
Pickling in Action 1311
Pickle Details: Protocols, Binary Modes, and _pickle 1314
Shelve Files 1315
Using Shelves 1316
Storing Built-in Object Types in Shelves 1317
Storing Class Instances in Shelves 1318
Changing Classes of Objects Stored in Shelves 1320
Shelve Constraints 1321
Pickled Class Constraints 1323
Other Shelve Limitations 1324
The ZODB Object-Oriented Database 1325
The Mostly Missing ZODB Tutorial 1326
SQL Database Interfaces 1329
SQL Interface Overview 1330
An SQL Database API Tutorial with SQLite 1332
Building Record Dictionaries 1339
Tying the Pieces Together 1342
Loading Database Tables from Files 1344
SQL Utility Scripts 1347
SQL Resources 1354
ORMs: Object Relational Mappers 1354
PyForm: A Persistent Object Viewer (External) 1356
18. Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1359
“Roses Are Red, Violets Are Blue; Lists Are Mutable,
and So Is Set Foo” 1359
Implementing Stacks 1360
Built-in Options 1360
A Stack Module 1362
A Stack Class 1364
Customization: Performance Monitors 1366
Optimization: Tuple Tree Stacks 1367
Optimization: In-Place List Modifications 1369
Timing the Improvements 1371
Implementing Sets 1373
Built-in Options 1374
Set Functions 1375
Set Classes 1377
Optimization: Moving Sets to Dictionaries 1378
Adding Relational Algebra to Sets (External) 1382
Subclassing Built-in Types 1383
Binary Search Trees 1385
Built-in Options 1385
Implementing Binary Trees 1386
Trees with Both Keys and Values 1388
Graph Searching 1390
Implementing Graph Search 1390
Moving Graphs to Classes 1393
Permuting Sequences 1395
Reversing and Sorting Sequences 1397
Implementing Reversals 1398
Implementing Sorts 1399
Data Structures Versus Built-ins: The Conclusion 1400
PyTree: A Generic Tree Object Viewer 1402
19. Text and Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1405
“See Jack Hack. Hack, Jack, Hack” 1405
Strategies for Processing Text in Python 1405
String Method Utilities 1406
Templating with Replacements and Formats 1408
Parsing with Splits and Joins 1409
Summing Columns in a File 1410
Parsing and Unparsing Rule Strings 1412
Regular Expression Pattern Matching 1415
The re Module 1416
First Examples 1416
String Operations Versus Patterns 1418
Using the re Module 1421
More Pattern Examples 1425
Scanning C Header Files for Patterns 1427
XML and HTML Parsing 1429
XML Parsing in Action 1430
HTML Parsing in Action 1435
Advanced Language Tools 1438
Custom Language Parsers 1440
The Expression Grammar 1440
The Parser’s Code 1441
Adding a Parse Tree Interpreter 1449
Parse Tree Structure 1454
Exploring Parse Trees with the PyTree GUI 1456
Parsers Versus Python 1457
PyCalc: A Calculator Program/Object 1457
A Simple Calculator GUI 1458
PyCalc—A “Real” Calculator GUI 1463
20. Python/C Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1483
“I Am Lost at C” 1483
Extending and Embedding 1484
Extending Python in C: Overview 1486
A Simple C Extension Module 1487
The SWIG Integration Code Generator 1491
A Simple SWIG Example 1491
Wrapping C Environment Calls 1495
Adding Wrapper Classes to Flat Libraries 1499
Wrapping C Environment Calls with SWIG 1500
Wrapping C++ Classes with SWIG 1502
A Simple C++ Extension Class 1503
Wrapping the C++ Class with SWIG 1505
Using the C++ Class in Python 1507
Other Extending Tools 1511
Embedding Python in C: Overview 1514
The C Embedding API 1515
What Is Embedded Code? 1516
Basic Embedding Techniques 1518
Running Simple Code Strings 1519
Running Code Strings with Results and Namespaces 1522
Calling Python Objects 1524
Running Strings in Dictionaries 1526
Precompiling Strings to Bytecode 1528
Registering Callback Handler Objects 1530
Registration Implementation 1531
Using Python Classes in C 1535
Other Integration Topics 1538
Part VI. The End
21. Conclusion: Python and the Development Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . 1543
“That’s the End of the Book, Now Here’s the Meaning of Life” 1544
“Something’s Wrong with the Way We Program Computers” 1544
The “Gilligan Factor” 1544
Doing the Right Thing 1545
The Static Language Build Cycle 1546
Artificial Complexities 1546
One Language Does Not Fit All 1546
Enter Python 1547
But What About That Bottleneck? 1548
Python Provides Immediate Turnaround 1549
Python Is “Executable Pseudocode” 1550
Python Is OOP Done Right 1550
Python Fosters Hybrid Applications 1551
On Sinking the Titanic 1552
So What’s “Python: The Sequel”? 1555
In the Final Analysis… 1555
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1557


Bookscreen
e-books shop

About This Book
This book is a tutorial introduction to using Python in common application domains
and tasks. It teaches how to apply Python for system administration, GUIs, and the
Web, and explores its roles in networking, databases, frontend scripting layers, text
processing, and more. Although the Python language is used along the way, this book’s
focus is on application to real-world tasks instead of language fundamentals.
Loading...
DMCA.com Protection Status