天天看點

學習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()