天天看点

学习Python (九)-- coding: utf-8 --

转载自龙腾测试

4 异常

4.1 异常

当程序中出现错误的情况,异常就发生了,Python会引发并告诉你那里有一个错误,从而处理这样的情况。

4.2 处理异常

我们可以使用try…except语句来处理异常。我们把通常的语句放在try块中,而把我们的错误出来语句放在except块中。

import sys

try:

s = input(‘请输入数字:’)

except NameError:

print’确认输入的是数字’

sys.exit()

print’完成’

4.3 引发异常

class ShortInputException(Exception):

def _ _ init _ _ (self,length,atleast):

Exception. _ _ init _ _ (self)

self.length = length

self.atleast = atleast

try:

s = raw_input(‘请输入至少3个字符:’)

if len(s) < 3:

raise ShortInputException(len(s),3)

except ShortInputException,x:

print ‘ShortInputException:输入的长度是%d,至少输入3个字符 %d’ %(x.length,x.atleast)

else:

print ‘没有异常被raise.’

4.4 try…finally

不管try子句中是否发生异常,finally子句都会被执行。

x = None

try:

x = 1 / 0

finally:

print ‘Cleaning up’

del x

4.5 try…except…else…finally

x = None

try:

x = 1 / 0

except ZeroDivisionError:

print ‘除数不能为0’

else:

print’未有异常’

finally:

print ‘Cleaning up’

del x

5 Assert

5.1 断言

在没完善一个程序之前,我们不知道程序在那里会出错,与其让它在运行时崩溃,不如在出现错误条件时就崩溃,这时就需要assert断言的帮助。

assert表达式[,参数]

assert 3 > 4,’le 3’

print ‘ok’

5.2 With…as

with open(‘test2.txt’) as f:

f.read()

这里使用了with语句,不管在处理文件过程中是否发生异常,都能保证with语句执行完毕后已经关闭了打开的文件句柄。

6 Python 标准库

6.1 sys模块

import sys

name = sys.argv[1]

print ‘your name is {0}’.format(name)

sys.stdout.endoding

‘UTF-8’

sys.version

‘2.7.9 (default, Dec 10 2014, 12:28:03) [MSC v.1500 64 bit (AMD64)]’

sys.getdefaultencoding()

‘ascii’

6.2 os模块

import os

for file in os.listdir(‘d:/’):

print file.decode(‘gbk’).encode(‘utf-8’)

os.name

‘nt’

os.getcwd()

‘D:\py’

os.system(‘dir’)

6.3 json

import json

d = dict(name=u’红楼梦’,total=10,lend=10)

json.dumps(d)

f = open(‘dump.json’,’wb’)

json.dump(d,f)

f.close()

f = open(‘dump.json’)

d= json.load(f)

f.close()

print json.dumps(d,indent=4)

dumps 把对象序列化为字符串,dump()直接把对象序列化后写入一个文件对象

6.4 xml

XML 被设计用来结构化、存储以及传输信息

-- coding: utf-8 --

import xml.etree.ElementTree as ET

tree = ET.ElementTree(file=’t.xml’)

for elem in tree.iter():

print elem.tag, elem.attrib, elem.text

对指定的tag进行遍历

-- coding: utf-8 --

import xml.etree.ElementTree as ET

tree = ET.ElementTree(file=’t.xml’)

for elem in tree.iter(tag=’sub-branch’):

print elem.tag, elem.attrib, elem.text

使用xpath

import xml.etree.ElementTree as ET

tree = ET.ElementTree(file=’t.xml’)

for elem in tree.iterfind(‘branch/sub-branch’):

print elem.tag, elem.attrib, elem.text

7 mysql

http://www.runoob.com/python/python-mysql.html

连接mysql

-- coding: UTF-8 --

import MySQLdb

打开数据库连接

db = MySQLdb.connect(“localhost”,”root”,”“,”test” )

使用cursor()方法获取操作游标

cursor = db.cursor()

使用execute方法执行SQL语句

cursor.execute(“SELECT VERSION()”)

使用 fetchone() 方法获取一条数据库。

data = cursor.fetchone()

print “Database version : %s ” % data

关闭数据库连接

db.close()

7.1 创建表

-- coding: UTF-8 --

import MySQLdb

打开数据库连接

db = MySQLdb.connect(“localhost”,”root”,”“,”test” )

使用cursor()方法获取操作游标

cursor = db.cursor()

如果数据表已经存在使用 execute() 方法删除表。

cursor.execute(“DROP TABLE IF EXISTS EMPLOYEE”)

创建数据表SQL语句

sql = “”“CREATE TABLE EMPLOYEE (

FIRST_NAME CHAR(20) NOT NULL,

LAST_NAME CHAR(20),

AGE INT,

SEX CHAR(1),

INCOME FLOAT )”“”

cursor.execute(sql)

关闭数据库连接

db.close()

7.2 插入数据

-- coding: UTF-8 --

import MySQLdb

打开数据库连接

db = MySQLdb.connect(“localhost”,”root”,”“,”test” )

使用cursor()方法获取操作游标

cursor = db.cursor()

SQL 插入语句

sql = “”“INSERT INTO EMPLOYEE(FIRST_NAME,

LAST_NAME, AGE, SEX, INCOME)

VALUES (‘Mac’, ‘Mohan’, 20, ‘M’, 2000)”“”

try:

# 执行sql语句

cursor.execute(sql)

# 提交到数据库执行

db.commit()

except:

# Rollback in case there is any error

db.rollback()

关闭数据库连接

db.close()

7.3 查询数据

-- coding: UTF-8 --

import MySQLdb

打开数据库连接

db = MySQLdb.connect(“localhost”,”root”,”“,”test” )

使用cursor()方法获取操作游标

cursor = db.cursor()

SQL 查询语句

sql = “SELECT * FROM EMPLOYEE \

WHERE INCOME > ‘%d’” % (1000)

try:

# 执行SQL语句

cursor.execute(sql)

# 获取所有记录列表

results = cursor.fetchall()

for row in results:

fname = row[0]

lname = row[1]

age = row[2]

sex = row[3]

income = row[4]

# 打印结果

print “fname=%s,lname=%s,age=%d,sex=%s,income=%d” % \

(fname, lname, age, sex, income )

except:

print “Error: unable to fecth data”

关闭数据库连接

db.close()

7.4 smtp

-- coding: utf-8 --

import smtplib

import sys

from email.mime.text import MIMEText

import getpass

发件人

sender = ‘###163.com’

收件人

receiver = sys.argv[1]

smtp服务器

server = ‘smtp.yeah.net’

标题

title = sys.argv[2]

内容

message = sys.argv[3]

账户

username = raw_input(‘user:’)

密码

password = getpass.getpass(‘password:’)

msg = MIMEText(message)

msg[‘Subject’] = title

msg[‘From’] = sender

msg[‘To’] = receiver

建立连接

s = smtplib.SMTP(server)

认证

s.login(username, password)

发送邮件

s.sendmail(sender,receiver.split(‘,’), msg.as_string())

s.quit()