Friday, July 11, 2008

Python Phrasebook - Essential Code and Commands

One of the most asked for feature in a book by programmers and coders is a quick reference for getting things done. That is, all the useful bits of code and other gems pertaining to a language compressed into a book whose size is ideal for carrying around where ever you go. Truth be told, there are not many such books around. When you search for a book which acts as a ready reference for any programming language, you inadvertently run into hefty 800 to 1000 page books which require significant effort on the part of the reader to navigate, let alone carry it around.

But the Phrasebook series is a set of books on a variety of programming languages which is published by Sams Publishing which aims to address this need. The advantage of the phrasebook is that it is small enough to be held in the palm of your hand. And the number of pages are no more than 300. Which means it is the exact dimension and size of an average pulp novel. But the difference is that each of those 300 pages contain a wealth of knowledge in the form of bits of useful code which can be readily used by programmers.

One such phrase book is the Python Phrasebook which has a very rich collection of customizable code snippets. "The Python Phrasebook - Essential code and commands" is authored by Brad Dayley and is divided into 10 distinct chapters each catering to a particular aspect of the Python language.

While the first chapter provides an overview of the Python language, the succeeding chapters provide bits of code in Manipulating strings in python, Managing data types, managing files, threads and databases in python and so on.

To highlight the usefulness of this little book, suppose I want to say find the right code to access a list using Python. I can do it in a number of ways. I could troll the internet to get the exact code, go through a good book on python which may or may not contain the exact code I want or make use of the easier way which is to use the Python phrasebook as a ready reference and find the exact code I am looking for in the "Managing data types" chapter. This little book contain a chapter on implementing internet communication where the author provides bits of code to achieve tasks related to sockets. And also chapters which show the code to process HTML and XML files using python.

One thing worth noting is that each code snippet is accompanied by an explanation of the code and also a short example program which utilize the code. This makes it much more easier for a Python programmer to understand the use of the code. And all code snippets address real life problems. So you will find code snippets to say, retrieve images from HTML documents, allowing users to upload files via CGI scripts, connecting to a MySQL database server, defining lists, splitting strings and so on which range from the common things to the other end of the spectrum of accomplishing specialized tasks.

To give a preview of what you get in this book, here is a sample excerpt from the Chapter 7 titled "Implementing Internet Communication".

Retrieving Email from a POP3 Server
The text below is the copyright of Sams Publishings.
mServer = poplib.POP3('mail.sfcn.org')
mServer.user(getpass.getuser())
mServer.pass_(getpass.getpass())
numMessages = len(mServer.list()[1])
for msg in mServer.retr(mList+1)[1]:
The code

The poplib module included with Python provides simple access to POP3 mail servers that allow you to connect and quickly retrieve messages using your Python scripts.

Connect to the POP3 mail server using the poplib.POP3(host [,port [,keyfile [,certfile]]]) method, where host is the address of the POP3 mail server. The optional port argument defaults to 995. The other optional arguments, keyfile and certfile, refer to the PEM-formatted private key and certificate authentication files, respectively.

To log in to the POP3 server, the code in pop3_mail.py calls the user(username) and pass_(password) methods of the POP3 server object to complete the authentication.

NOTE: The example uses getuser() and getpass() from the getpass module to retrieve the username and password. The username and password can also be passed in as clear text strings.

After it’s authenticated to the POP3 server, the poplib module provides several methods to manage the mail messages. The example uses the list() method to retr ieve a list of messages in the tuple format (response, msglist, size), where response is the server’s response code, msglist is a list of messages in string format, and size is the size of the response in bytes.

To retrieve only a single message, use retr(msgid). The retr method retur ns the message numbered msgid in the form of a tuple (response, lines, size), where response is the server response, lines is a list of strings that com- pose the mail message, and size is the total size in bytes of the message.

NOTE: The lines list returned by the retr method includes all lines of the messages, including the head- er. To retrieve specific information, such as the recipi- ent list, the lines list must be parsed.

When you are finished managing the mail messages, use the quit() method to close the connection to the POP3 server.

import poplib
import getpass
mServer = poplib.POP3('mail.sfcn.org')
#Login to mail server
mServer.user(getpass.getuser())
mServer.pass_(getpass.getpass())
#Get the number of mail messages
numMessages = len(mServer.list()[1])
print "You have %d messages." % (numMessages)
print "Message List:"
#List the subject line of each message
for mList in range(numMessages) :
for msg in mServer.retr(mList+1)[1]:
if msg.startswith('Subject'):
print '\t' + msg
Using Python to Fetch Files from an FTP Server 159
break
mServer.quit()
The Program : pop3_mail.py

password:
You have 10 messages.
Message List:
Subject: Static IP Info
Subject: IP Address Change
Subject: Verizon Wireless Online Statement
Subject: New Static IP Address
Subject: Your server account has been created
Subject: Looking For New Home Projects?
Subject: PDF Online - cl_scr_sheet.xls
Subject: Professional 11 Upgrade Offer
Subject: #1 Ball Played at the U.S. Open
Subject: Chapter 3 submission
The Output: From pop3_mail.py code above

Book Specification
Name : Python Phrasebook - Essential code and commands
ISBN No: 0-672-32910-7
Author : Brad Dayley
Publisher : Sams Publishing
No of Pages : 300
Price : Check the latest price at Amazon.com
Comments : An Ideal resource for Python programmers. Acts as a ready made code source for achieving a variety of tasks in Python.

No comments: