花了几个小时把A Byte of Python看完以后,我觉得Python确实是简洁易用。
A Byte of Python最后面让大家写一个Command line address book练一下手,
于是就有了我的第一个Python程序了,直接上代码,没什么好解释的。
#!/usr/bin/python2
# Filename: address_book.py
import os
import sys
import cPickle as p
import smtplib
import getpass
def printHelp():
print '''\
This is a simple address book.
action:
add | insert -- add/insert a contact
del | delete -- delete a contact
search | lookup -- search email by name
send -- send email to a contact
quit | exit -- exit this program
help -- print this help\
'''
def add(ab):
name = raw_input('\tName\t: ')
email = raw_input('\tEmail\t: ')
ab[name] = email
def delete(ab):
name = raw_input('\tName\t: ')
del ab[name]
def search(ab):
name = raw_input('\tName\t: ')
if name in ab:
print 'Name: %s\tEmail:%s' %(name, ab[name])
else:
print 'No contact %s found' %name
def send(ab):
name = raw_input('\tName\t: ')
if name in ab:
username = raw_input('Username: ')
password = getpass.getpass('Password: ')
From = os.getenv('EMAIL')
if From is None:
From = raw_input('From: ')
To = ab[name]
Subject = raw_input('Subject: ')
Text = raw_input('Text: ')
Text = "" + Text + ""
Header = ["From: " + From,
"Subject: " + Subject,
"To: " + To,
"MIME-Version: 1.0",
"Content-Type: text/html"]
Header = '\r\n'.join(Header)
Host = 'smtp.gmail.com:587'
server = smtplib.SMTP(Host)
server.starttls()
print 'Login...'
server.login(username, password)
print 'Sending mail...'
server.sendmail(From, To, Header + '\r\n\r\n' + Text)
server.quit()
print 'Finish.'
else:
print 'No contact %s found' %name
def save(ab, filename):
f = file(filename, 'w')
p.dump(ab, f)
f.close()
# Script begins here
if len(sys.argv) != 2:
print 'Usage: %s <filename>' %sys.argv[0]
sys.exit()
# Initialize
ab = {}
filename = sys.argv[1]
if os.path.exists(filename):
if not os.path.isfile(filename):
print '%s is not a file.' %filename
sys.exit()
else:
f = file(filename)
try:
ab = p.load(f)
except EOFError:
pass
except:
print 'load %s error' %filename
f.close()
sys.exit()
f.close()
# main loop
while True:
try:
action = raw_input('Enter action-->:')
except EOFError:
continue
except:
save(ab, filename)
if (action == 'add' or action == 'insert'):
add(ab)
elif (action == 'delete' or action == 'del'):
delete(ab)
elif (action == 'search' or action == 'lookup'):
search(ab)
elif (action == 'send'):
send(ab)
elif (action == 'exit' or action == 'quit'):
save(ab, filename)
sys.exit()
else:
printHelp()