文件名称:
programmingpython-ch15.pdf
开发工具:
文件大小: 3mb
下载次数: 0
上传时间: 2019-08-18
详细说明:“Use the Source, Luke”
TheprecedingchapterintroducedPython’sclient-sideInternettoolset—thestan-
dardlibrarymodulesavailableforemail,FTP,networknews,andmore,fromwithin
aPythonscript.Thischapterpicksupwherethelastoneleftoffandpresentsacom-
pleteclient-sideexample—PyMailGUI,aPythonprogramthatsends,recen1522420 Page 878 Friday, August 11, 2006 1: 03 PM
Finally, the following are new modules coded in this chapter and are specific to the
Py Mailgui program
SharedNames py
Program-wide globals used by multiple files
ViewWindows py
The implementation of View, Write, Reply, and Forward message view windows
Listwindows py
The implementation of mail-server and local-file message list windows
PyMailGuiHelp2 py
User-oriented help text, opened by the main window' s bar button
The main, top-level file of the program, run to launch the main window
All told, PythonMailGUI comprises the nine new modules in the preceding two lists
and is composed of some 2, 200 lines of source code (including comments
whitespace, and 530 lines of help text). This doesn't include the four other book
examples in the previous list that are reused in PyMailGUl, which themselves consti-
tute 1, 600 additional lines. This is the largest example we'll see in this book, but you
shouldnt be deterred by its size. Because it uses modular and Oop techniques, the
code is simpler than you may think
Python's modules allow us to divide the system into files that have a cohesive
purpose, with minimal coupling between them--code is easier to locate and
understand if your modules have a logical, self-contained structure
Pythons OOP support allows us to factor code for reuse, and avoid redun
dancy--as you'll see, code is customized, not repeated, and the classes we will
code reflect the actual components of the gui to make them easy to follow
For instance, the implementation of mail list windows is easy to read and change
because it has been factored into a common shared superclass, which is customized
by subclasses for mail-server and save-file lists; since these are mostly just variations
on a theme, most of the code appears in just one place. Similarly, the code that imple
ments the message view window is a superclass shared by write, reply, and forward
composition windows; subclasses simply tailor it for writing rather than viewing
Although we'll deploy these techniques in the context of a mail processing program
here, such techniques will apply to any nontrivial program you' ll write in Python
And remember: you would have to multiply these line counts by a factor of four or five to get the equivalent
in a language like C or C++. If you've done much programming, you probably recognize that the fact that
we can implement a fairly full-featured mail processing program in roughly 2,000 lines of code speaks vol
umes about the power of the Python language and its libraries. For comparison, the original version of this
program from thc sccond edition of this book was just 725 lincs in 3 new modules, but also was vcry lim
d-it did not sur
Py Mailgul2's attach
thread overlap local mail files, and
878 Chapter 15: The PyMailGUI Cli
分
n1522420 Page 879 Friday, August 11, 2006 1: 03 PM
To help get you started, the PyMailGuiHelp2 py module listed last in this chapter
includes a help text string that describes how this program is used, as well as its
major features. Experimenting with the system, while referring to its code, is proba
bly the best and quickest way to uncover its secrets
Why PyMailGUI?
PyMailGUI is a Python program that implements a client-side email processing user
interface with the standard Tkinter gui toolkit It is presented both as an instance of
Python Internet scripting and as a realistically scaled example that ties together other
tools we' ve already seen such as threads and Tkinter guis
Like the pymail console-based program we wrote in Chapter 14, PyMailGUI runs
entirely on your local computer. Your email is fetched from and sent to remote mail
servers over sockets, but the program and its user interface run locally. As a result,
PyMailGUI is called an email client like pymail, it employs Pythons client-side tools
Lo talk to mail servers from the local machine. Unlike pymail, though, Py MailGUI is a
full-featured user interface: email operations are performed with point-and-click
operations and advanced mail processing such as attachments and save files is
supported
Like many examples presented in this text, PyMailGUI is a practical, useful pro
gram. In fact, I run it on all kinds of machines to check my email while traveling
around the world teaching Python classes. Although PyMailGUI wont put Microsoft
Outlook out of business anytime soon, it has two key pragmatic features that have
nothing to do with email itself: portability and scriptability, which are attractive fea
tures in their own right and they merit a few additional words here
It's portable
Py MailGUI runs on any machine with sockets and a Python with Tkinter
installed. Because email is transferred with the Python libraries, any Internet
connection that supports Post Office Protocol (POP) and Simple Mail Transfer
Protocol (SMTP)access will do. Moreover, because the user interface is coded
with Tkinter, Py Mail GUI Should work, unchanged, on Windows, the X Win
dow System(Unix, Linux), and the Macintosh(classic and OS X)
Microsoft Outlook may be a more feature-rich package, but it has to be run on
Windows, and more specifically, on a single Windows machine. Because it gen
erally deletes email from a server as it is downloaded and stores it on the client,
you cannot run Outlook on multiple machines without spreading your email
across all those machines. By contrast, Py MailGUI saves and deletes email onl
on request, and so it is a bit friendlier to people who check their email in an ad
c fashion on arbit
"Use the source luke
分
n15.22420 Page 880 Friday, August 11, 2006 1: 03 PM
It's scriptable
Py MailguI can become anything you want it to be because it is fully program-
mable. In fact, this is the real killer feature of Py MailGUI and of open source
software like Python in general-because you have full access to Py MailGUI's
source code, you are in complele control of where it evolves from here. You have
nowhere near as much control over commercial, closed products like Outlook
you generally get whatever a large company decided you need, along with what-
ever bugs that company might have introduced
As a Python script, Py MailGUI is a much more flexible tool. For instance, we
can change its layout, disable features, and add completely new functionality
quickly by changing its Python source code. Don't like the mail-list display?
Change a few lines of code to customize it want to save and delete your mail
automatically as it is loaded? Add some more code and buttons. Tired of seeing
junk mail? Add a few lines of text processing code to the load function to filter
spam. These are just a few examples. The point is that because Py MailGUI is
written in a high-level, easy-to-maintain scripting language, such customizations
are relatively simple, and might even be fun
At the end of the day, because of such features, this is a realistic Python program that
I actually use-both as a primary email tool and as a fallback option when my iSP's
webmail system goes down (which, as I mentioned in the prior chapter, has a way of
happening at the worst possible times). Python scripting is an enabling skill to have
It's also worth mentioning that Py MailguI achieves its portability and scriptability,
and implements a full-featured email interface along the way, in roughly 2, 200 lines
of program code. It may not have all the bells and whistles of some commercial prod-
ucts, but the fact that it gets as close as it does in so few lines of code is a testament
to the power of both the python language and its libraries
Running PyMailGUl
Of course, to script Py mailGUI on your own, you'll need to be able to run it
PyMailgui requires only a computer with some sort of internet connectivity (a pc
with a broadband or dial-up account will do)and an installed Python with the
Tkinter extension enabled. The Windows port of Python has this capability, so Win
dows pc users should be able to run this program immediately by clicking its icon
Two notes on running the system: first, you'll want to change the file mailconfig py
in the program s source directory to reflect your account s parameters, if you wish to
send or receive mail from a live server; more on this as we interact with the system
In fact, my ISP's webmail send system went down the very day i had to submit this edition of the book to
my publisher! No worrics--I fired up Py MailGUI and uscd it to send the book as attachment files through
a different server. In a sense, this bock submitted itselt
880 Chapter 15: The PyMailGUI Client
分
h1522420 Page 881 Friday, August 11, 2006 1: 03 PM
Second, you can still experiment with the system without a live Internet connec-
tion--for a quick look at message view windows, use the main windows Open but
tons to open saved-mail files stored in the programs Savedmail directory In fact, the
Py
Demos launcher script at the top of the books examples directory forces
Py Mailgui Lo open saved-Imail files by passing filenames on the command line
Presentation Strategy
Py MailGUi is easily the largest program in this book, but it doesn t introduce many
library interfaces that we haven t already seen in this book. For instance
The PyMailGUI interface is built with Pythons Tkinter, using the familiar list-
boxes, buttons, and text widgets we met earlier
Pythons email package is applied to pull-out headers, text, and attachments of
messages, and to compose the same
ython's POP and SMTP library modules are used to fetch, send, and delete mail
over sockets
Python threads, if installed in your Python interpreter, are put to work to avoid
blocking during potentially overlapping, long-running mail operations
Were also going to reuse the TextEditor object we wrote in Chapter 12 to view and
compose messages, the mailtools package's tools we wrote in Chapter 14 to load
and delete mail from the server, and the mailconfig module strategy introduced
Chapter 14 to support end-user settings. Py MailGUI is largely an exercise in combin-
ing existing tools
On the other hand, because this program is so long, we won't exhaustively docu-
ment all of its code. Instead, we 'll begin by describing how py mailgUI works from
an end user's perspective a brief demo of its windows in action After that, we'll list
the system's new source code modules without many additional comments, for fur-
ther study
Like most of the longer case studies in this book this section assumes that you
a ready know enough Python to make sense of the code on your own. If you've been
reading this book linearly, you should also know enough about Tkinter, threads, and
nail interfaces to understand the library tools applied here. If you get stuck, you may
wish to brush up on the presentation of these topics earlier in the book
New in this edition
The 2. 1 version of Py mailGui presented in this third edition of the book is a com
plete rewrite of the 1.0 version of the prior edition The main script in the second
edition s version was only some 500 lines long, and was really something of a toy or
prototype, written mostly to serve as a book example. In this edition, Py MailgUI is a
much more realistic and full-featured program that can be used for day-to-day email
"Use the source luke
881
分
n1522420 Page 882 Friday, August 11, 2006 1: 03 PM
processing. It has grown to 2, 200 source lines (3, 800 including related modules that
are reused). Among its new weapons are these
MIME multipart mails with attachments may be both viewed and composed
Mail transfers are no longer blocking, and may overlap in time
Mail may be saved and processed offline from a local file
Message parts may now be opened automatically within the guI
Multiple messages may be selected for processing in list windows
Initial downloads fetch mail headers only; full mails are fetched on request
View window headers and list window columns are configurable
Deletions are performed immediately, not delayed until program exit
Most server transfers report their progress in the GuI
Long lines are intelligently wrapped in viewed and quoted text
Fonts and colors in list and view windows may be configured by the user.
Authenticating SMTP mail-send servers that require login are supported.
Sent messages are saved in a local file, which may be opened in the gui
View windows intelligently pick a main text part to be displayed
Already fetched mail headers and full mails are cached for speed
Date strings and addresses in composed mails are formatted properly
View windows now have quick-access buttons for attachments/parts(2. 1)
Inbox out-of-sync crrors are detected on deletes, and on index and mail loads
Save-mail file loads and deletes are threaded, to avoid pauses for large files(2.1)
The last three items on this list were added in version 2.1; the rest were part of the 2.0
rewrite. Some of these changes were made simple by growth in standard library tools
(e. g, support for attachments is straightforward with the new email package), but
most represent changes in PyMailGUI itselt. There have also been a few genuine fixes
addresses are parsed more accurately, and date and time formats in sent mails are now
g, because these tasks use new tools in the email package
Although there is still room for improvement(see the list at the end of this chapter)
the program provides a full-featured interface, represents the most substantial exam
le in this book and
to demonstrate a realistic appl
of the python lan
guage. As its users often attest, Python may be fun lo work with, but it's also useful
or writing pi
cal and nontrivial softy
882 Chapter 15: The PyMailGUI Cli
分
n1522420 Page 883 Friday, August 11, 2006 1: 03 PM
A PyMailGUI Demo
Py MailGUI is a multiwindow interface. It consists of the following
A main mail-server list window opened initially, for online mail processing
One or more mail save-file list windows for offline mail processing
One or more mail-view windows for viewing and editing messages
Text editor windows for displaying the systems source code
Nonblocking busy state pop-up dialogs
Assorted pop-up dialogs for opened message parts, help, and more
Operationally, PyMailGUI runs as a set of parallel threads, which may overlap in
time: one for each active server transfer and one for each active offline save file load
or deletion. Py MailGUI supports mail save files, automatic saves of sent messages
configurable fonts and colors, viewing and adding attachments, main message text
extraction and much more
To make this case study easier to understand, let's begin by seeing what Py MailGUI
actually doesits user interaction and email processing functionality-before jump
into the pytho
As
d this
free to jump ahead to the code listings that appear after the screenshots, but be sure
to read this section too; this is where some subtleties of PyMailGUI's design are
explained. After this section, you are invited to study the systems Python source
code listings on your own for a better and more complete explanation than can be
crafted in english
Getting Started
Py MailGUI is a Python/Tkinter program, run by executing its top-level script file
Py MailGui. py. Like other Python programs, Py MailGUI can be started from the sys-
tem command line by clicking on its filename icon in a tile explorer interface, or b
pressing its button in the Py Demos or Py Gadgets launcher bar. However it is started
the first window PyMailGUI presents is shown in Figure 15-1. Notice the"PY"win
dow icon: this is the handiwork of window protocol tools we wrote earlier in this
book
This is the Py MailGUI main window -every operation starts here. It consists of
a help button (the bar at the top
A clickable email list area for fetched emails(the middle section)
a button bar at the bottom for processing messages selected in the list area
A PyMailGUI Demo 883
分
n15.22420 Page 884 Friday, August 11, 2006 1: 03 PM
吧Macu21 pop. car thlink nct
□回
PM减 iGUl·aFyn' Tkinter enail client help
U10Ew:Ew:SkiinginDubailutzrm.net
Fri,27an200602:44:19
arthllnk alert: Unileve Earth¢ ustomer stpor上r,2 d Jan 200b l3:l:四
*012 Returned mail: delivery p Mail Delivery Subsystem 29 Jan 2006 5:38: 47+000
013 testing smtp
I lut z(rTn.net
su,29Jan200615:30:30
014 Returned mail: delivery p Mail Delivery Subsystem( 30 Jan 2006 8: 07: 51 +000
01] ELink #89: Print on Deman EarthLink Newsletter staf I Mon, 30 Jan 2006 13: 19: 08
*016ItestsendwindowupdatesIppeearthlink.net
Exi,03Eeh200623:45:09
017 Re: Merica MPs file
rp segearthlink net
sat,04Eeh200600:23:2
o18 Re: testing sntp
p3ecearthlink, net
sat,04Ee200600:33:11
ng testing 12
I pp3elearthl1nknet
sm,05Ee200:4:29
Load view Delete. e REply Fwd Save Open Guit
Figure 15-1. Py MailG UI main server list window
In normal operation, users load their email, select an email from the list area by click-
ing on it, and press a button at the bottom to process it No mail messages are shown
initially; we need to first load them with the Load button--a simple password input
dialog is displayed, a busy dialog appears that counts down message headers being
loaded to give a status indication, and the index is filled with messages ready to be
selected
Py MailGUI's list windows, such as the one in Figure 15-1, display mail header details
in fixed-width columns, up to a maximum size Mails with attachments are prefixed
with a "* in mail index list windows, and fonts and colors in Py mailgui windows
may be customized by the user in the mailconfig configuration file. You can't tell in
this black-and white book but by default, mail index lists are Indian red, view win-
dows are a shade of purple, pop-up Py Edit windows are light cyan, and help is steel
blue, you can change most of these as you like(see Example 9-11 for help with color
definition strings)
List windows allow multiple messages to be selected at once-the action selected at
the bottom of the window is applied to all selected mails. For instance, to view many
De
Isplayed in its own
view window. Use Ctrl-Click and Shift-Click to select more than one(the standard
Windows multiple selection operations apply--try it)
Before we go any further, though, let's press the help bar at the top of the list win-
dow in Figure 1.5-1 to see what sort of help is available, Figure 1.5-2 shows the help
window popup that appears
The main part of this window is simply a block of text in a scrolled -Lext widget,
along with two buttons at the bottom. The entire help text is coded as a single triple
quoted string in the Python program. We could get fancier and spawn a web browser
884 Chapter 15: The PyMailGUI Client
分
n1522420 Page 885 Friday, August 11, 2006 1: 03 PM
PY PYMailGUl 2. 1-Help
yMailGUl, version 2.1
anuary, 2006
Programming Python, rd Fditinn
ORellly Medla, Inc.
PyMailGUl is a multi-window interface for processing email, both on-line and
off-line Its main inte rfaces include one list window for the mail server
zero or more list windows for mail save files, and multiple view windows for
composIng or viewIng malls selected In a llst wIndow. On start-up, the maIn
erver] list window appears first, but no mail server connection is attempted
itil a Load or message send request. All PyMailGUl windows may be resized,
which is especially useful in list windows to see additional columns
Major enhancements in this version
MIME multi-part mails with attachments may be both viewed and composed
Mail transfers are nn Innger hInrking, and may nverlan in time
Mail may be saved and processed off-line from a local file
Message parts may now be opened automatically within the GUI
Multiple messages may be selected for processing in list windows
Initial downloads fetch mail headers only full mails are fetched on request
view window headers and list window columns are rnnfinurahIe
Deletions are performed im mediately, not delayed until program exit.
SouiceCancel
Figure 15-2. PyMailGUI help popup
to view HTMI- formatted help, but simple text does the job here. The Cancel but-
ton makes this nonmodal (i.e, nonblocking)window go away; more interestingly
the Source button pops up pyEdit text editor viewer windows for all the source files
of PyMailGUIs implementation; Figure 15-3 captures one of these(there are
many--this is intended as a demonstration, not as a development environment). not
every program shows you its source code, but PyMailGUI follows Python's open
source motif
When a message is selected in the mail list window, Py MailGuI downloads its full
text (if it has not yet been downloaded in this session), and an email viewer window
appears, as captured in Figure 15-4. View windows are built in response to actions in
list windows this is described next
The standard librarys webbrowser module would help for HTML-based help. Actually, the help display
starred life even less fancy: it originally displayed help text in a standard information box pop up, generated
by the tkinter showinfo call used earlier in the book. This worked fine on Windows(at least with a small
amount of help text), but it failed on Linux bccausc of a default linc-lcngth limit in information pop-up
boxes; lines were broken so badly as to be illegible
A PyMailGUI Demo 88
分
(系统自动生成,下载前可以参看下载内容)
下载文件列表
相关说明
- 本站资源为会员上传分享交流与学习,如有侵犯您的权益,请联系我们删除.
- 本站是交换下载平台,提供交流渠道,下载内容来自于网络,除下载问题外,其它问题请自行百度。
- 本站已设置防盗链,请勿用迅雷、QQ旋风等多线程下载软件下载资源,下载后用WinRAR最新版进行解压.
- 如果您发现内容无法下载,请稍后再次尝试;或者到消费记录里找到下载记录反馈给我们.
- 下载后发现下载的内容跟说明不相乎,请到消费记录里找到下载记录反馈给我们,经确认后退回积分.
- 如下载前有疑问,可以通过点击"提供者"的名字,查看对方的联系方式,联系对方咨询.