70 The Python Book
Python essentials
40. Sending email
You can use the module ‘smtplib’ to send email
using an SMTP (Simple Mail Transfer Protocol)
client interface.
smtplib.SMTP([host [, port]])
Example (send an email using Google Mail
SMTP server):
import smtplib
# Use your own to and from email
address
fromaddr = ‘
[email protected]’
toaddrs = ‘
[email protected]’
msg = ‘I am a Python geek. Here is
the proof.!’
# Credentials
# Use your own Google Mail
credentials while running the
program
username = ‘
[email protected]’
password = ‘xxxxxxxx’
# The actual mail send
server = smtplib.SMTP(‘smtp.gmail.
com:587’)
# Google Mail uses secure
connection for SMTP connections
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs,
msg)
server.quit()
41. Accessing
FTP server
‘ftplib’ is a fully fledged client FTP module for
Python. To establish an FTP connection, you
can use the following function:
ftplib.FTP([host [, user [, passwd
[, acct [, timeout]]]]])
Example:
host = “ftp.redhat.com”
username = “anonymous”
password = “
[email protected]”
import ftplib
import urllib2
ftp_serv = ftplib.
FTP(host,username,password)
# Download the file
u = urllib2.urlopen (“ftp://
ftp.redhat.com/pub/redhat/linux/
README”)
# Print the file contents
print (u.read())
Output:
[~/src/python $:] python
ftpclient.py
Older versions of Red Hat Linux have been moved
to the following location: ftp://archive.download.
redhat.com/pub/redhat/linux/
42. Launching a webpage
with the default web
browser
The ‘webbrowser’ module provides a convenient
way to launch webpages using the default
web browser.
Example (launch google.co.uk with system’s
default web browser):
>>> import webbrowser
>>> webbrowser.open(‘http://google.
co.uk’)
True
43. Creating secure hashes
The ‘hashlib’ module supports a plethora of
secure hash algorithms including SHA1, SHA224,
SHA256, SHA384, SHA512 and MD5.
Example (create hex digest of the given text):
>>> import hashlib
# sha1 Digest
>>> hashlib.sha1(“MI6 Classified
Information 007”).hexdigest()
‘e224b1543f229cc0cb935a1eb9593
18ba1b20c85’
# sha224 Digest
>>> hashlib.sha224(“MI6 Classified
Information 007”).hexdigest()
‘3d01e2f741000b0224084482f905e9b7b97
7a59b480990ea8355e2c0’
# sha256 Digest
>>> hashlib.sha256(“MI6 Classified
Information 007”).hexdigest()
‘2fdde5733f5d47b67 2fcb39725991c89
b2550707cbf4c6403e fdb33b1c19825e’
# sha384 Digest
>>> hashlib.sha384(“MI6 Classified
Information 007”).hexdigest()
‘5c4914160f03dfbd19e14d3ec1e74bd8b99
dc192edc138aaf7682800982488daaf540be
9e0e50fc3d3a65c8b6353572d’
# sha512 Digest
>>> hashlib.sha512(“MI6 Classified
Information 007”).hexdigest()
‘a704ac3dbef6e8234578482a31d5ad29d25
2c822d1f4973f49b850222edcc0a29bb89077
8aea807a0a48ee4ff8bb18566140667fbaf7
3a1dc1ff192febc713d2’
# MD5 Digest
>>> hashlib.md5(“MI6 Classified
Information 007”).hexdigest()
‘8e2f1c52ac146f1a999a670c826f7126’
44. Seeding random
numbers
You can use the module ‘random’ to generate
a wide variety of random numbers. The most
used one is ‘random.seed([x])’. It initialises
the basic random number generator. If x is
omitted or None, current system time is used;
current system time is also used to initialise the
generator when the module is first imported.
45. Working with CSV
(comma-separated
values) files
CSV files are very popular for data exchange over
the web. Using the module ‘csv’, you can read and
write CSV files.
Example:
import csv
# write stocks data as comma-
separated values
writer = csv.writer(open(‘stocks.
csv’, ‘wb’, buffering=0))
writer.writerows([
(‘GOOG’, ‘Google, Inc.’, 505.24, 0.47,
0.09),
(‘YHOO’, ‘Yahoo! Inc.’, 27.38, 0.33,
1.22),
(‘CNET’, ‘CNET Networks, Inc.’, 8.62,
-0.13, -1.49)
])
# read stocks data, print status
messages
stocks = csv.reader(open(‘stocks.
csv’, ‘rb’))
status_labels = {-1: ‘down’, 0:
‘unchanged’, 1: ‘up’}
for ticker, name, price, change, pct
in stocks:
status = status_
labels[cmp(float(change), 0.0)]
print ‘%s is %s (%s%%)’ % (name,
status, pct)
46. Installing third-
party modules using
setuptools
‘setuptools’ is a Python package which lets you
download, build, install, upgrade and uninstall
packages very easily.
To use ‘setuptools’ you will need to install
from your distribution’s package manager.
After installation you can use the command
‘easy_install’ to perform Python package
management tasks.