日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

Python基础教程(十一):多线程、XML解析

發(fā)布時間:2025/3/21 asp.net 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python基础教程(十一):多线程、XML解析 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Python使用SMTP發(fā)送郵件

SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協(xié)議,它是一組用于由源地址到目的地址傳送郵件的規(guī)則,由它來控制信件的中轉(zhuǎn)方式。

python的smtplib提供了一種很方便的途徑發(fā)送電子郵件。它對smtp協(xié)議進行了簡單的封裝。

Python創(chuàng)建 SMTP 對象語法如下:

import smtplib ? smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

參數(shù)說明:

  • host: SMTP 服務(wù)器主機。 你可以指定主機的ip地址或者域名如:w3cschool.cc,這個是可選參數(shù)。
  • port: 如果你提供了 host 參數(shù), 你需要指定 SMTP 服務(wù)使用的端口號,一般情況下SMTP端口號為25。
  • local_hostname: 如果SMTP在你的本機上,你只需要指定服務(wù)器地址為 localhost 即可。

Python SMTP對象使用sendmail方法發(fā)送郵件,語法如下:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

參數(shù)說明:

  • from_addr: 郵件發(fā)送者地址。
  • to_addrs: 字符串列表,郵件發(fā)送地址。
  • msg: 發(fā)送消息

這里要注意一下第三個參數(shù),msg是字符串,表示郵件。我們知道郵件一般由標(biāo)題,發(fā)信人,收件人,郵件內(nèi)容,附件等構(gòu)成,發(fā)送郵件的時候,要注意msg的格式。這個格式就是smtp協(xié)議中定義的格式。

實例

以下是一個使用Python發(fā)送郵件簡單的實例:

#!/usr/bin/python ? import smtplib ? sender = 'from@fromdomain.com' receivers = ['to@todomain.com'] ? message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> Subject: SMTP e-mail test ? This is a test e-mail message. """ ? try: ?? smtpObj = smtplib.SMTP('localhost') ?? smtpObj.sendmail(sender, receivers, message)???????? ???print "Successfully sent email" except SMTPException: ?? print "Error: unable to send email"

使用Python發(fā)送HTML格式的郵件

Python發(fā)送HTML格式的郵件與發(fā)送純文本消息的郵件不同之處就是將MIMEText中_subtype設(shè)置為html。具體代碼如下:

import smtplib? from email.mime.text import MIMEText? mailto_list=["YYY@YYY.com"] mail_host="smtp.XXX.com"? #設(shè)置服務(wù)器 mail_user="XXX"??? #用戶名 mail_pass="XXXX"?? #口令 mail_postfix="XXX.com"? #發(fā)件箱的后綴 ? def send_mail(to_list,sub,content):? #to_list:收件人;sub:主題;content:郵件內(nèi)容 ??? me="hello"+"<"+mail_user+"@"+mail_postfix+">"?? #這里的hello可以任意設(shè)置,收到信后,將按照設(shè)置顯示 ??? msg = MIMEText(content,_subtype='html',_charset='gb2312')??? #創(chuàng)建一個實例,這里設(shè)置為html格式郵件 ??? msg['Subject'] = sub??? #設(shè)置主題 ??? msg['From'] = me? ????msg['To'] = ";".join(to_list)? ????try:? ????????s = smtplib.SMTP()? ????????s.connect(mail_host)? #連接smtp服務(wù)器 ??????? s.login(mail_user,mail_pass)? #登陸服務(wù)器 ??????? s.sendmail(me, to_list, msg.as_string())? #發(fā)送郵件 ??????? s.close()? ????????return True? ????except Exception, e:? ????????print str(e)? ????????return False? if __name__ == '__main__':? ????if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五義</a>"):? ????????print "發(fā)送成功"? ????else:? ????????print "發(fā)送失敗"?

或者你也可以在消息體中指定Content-type為text/html,如下實例:

#!/usr/bin/python ? import smtplib ? message = """From: From Person <from@fromdomain.com> To: To Person <to@todomain.com> MIME-Version: 1.0 Content-type: text/html Subject: SMTP HTML e-mail test ? This is an e-mail message to be sent in HTML format ? <b>This is HTML message.</b> <h1>This is headline.</h1> """ ? try: ?? smtpObj = smtplib.SMTP('localhost') ?? smtpObj.sendmail(sender, receivers, message)???????? ???print "Successfully sent email" except SMTPException: ?? print "Error: unable to send email"

Python發(fā)送帶附件的郵件

發(fā)送帶附件的郵件,首先要創(chuàng)建MIMEMultipart()實例,然后構(gòu)造附件,如果有多個附件,可依次構(gòu)造,最后利用smtplib.smtp發(fā)送。

from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib ? #創(chuàng)建一個帶附件的實例 msg = MIMEMultipart() ? #構(gòu)造附件1 att1 = MIMEText(open('d:\\123.rar', 'rb').read(), 'base64', 'gb2312') att1["Content-Type"] = 'application/octet-stream' att1["Content-Disposition"] = 'attachment; filename="123.doc"'#這里的filename可以任意寫,寫什么名字,郵件中顯示什么名字 msg.attach(att1) ? #構(gòu)造附件2 att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312') att2["Content-Type"] = 'application/octet-stream' att2["Content-Disposition"] = 'attachment; filename="123.txt"' msg.attach(att2) ? #加郵件頭 msg['to'] = 'YYY@YYY.com' msg['from'] = 'XXX@XXX.com' msg['subject'] = 'hello world' #發(fā)送郵件 try: ??? server = smtplib.SMTP() ??? server.connect('smtp.XXX.com') ??? server.login('XXX','XXXXX')#XXX為用戶名,XXXXX為密碼 ??? server.sendmail(msg['from'], msg['to'],msg.as_string()) ??? server.quit() ??? print '發(fā)送成功' except Exception, e:? ????print str(e)

以下實例指定了Content-type header 為multipart/mixed,并發(fā)送/tmp/test.txt 文本文件:

#!/usr/bin/python ? import smtplib import base64 ? filename = "/tmp/test.txt" ? # 讀取文件內(nèi)容并使用 base64 編碼 fo = open(filename, "rb") filecontent = fo.read() encodedcontent = base64.b64encode(filecontent)? # base64 ? sender = 'webmaster@tutorialpoint.com' reciever = 'amrood.admin@gmail.com' ? marker = "AUNIQUEMARKER" ? body =""" This is a test email to send an attachement. """ # 定義頭部信息 part1 = """From: From Person <me@fromdomain.net> To: To Person <amrood.admin@gmail.com> Subject: Sending Attachement MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=%s --%s """ % (marker, marker) ? # 定義消息動作 part2 = """Content-Type: text/plain Content-Transfer-Encoding:8bit ? %s --%s """ % (body,marker) ? # 定義附近部分 part3 = """Content-Type: multipart/mixed; name=\"%s\" Content-Transfer-Encoding:base64 Content-Disposition: attachment; filename=%s ? %s --%s-- """ %(filename, filename, encodedcontent, marker) message = part1 + part2 + part3 ? try: ?? smtpObj = smtplib.SMTP('localhost') ?? smtpObj.sendmail(sender, reciever, message) ?? print "Successfully sent email" except Exception: ?? print "Error: unable to send email"

?

?

Python 多線程

多線程類似于同時執(zhí)行多個不同程序,多線程運行有如下優(yōu)點:

  • 使用線程可以把占據(jù)長時間的程序中的任務(wù)放到后臺去處理。
  • 用戶界面可以更加吸引人,這樣比如用戶點擊了一個按鈕去觸發(fā)某些事件的處理,可以彈出一個進度條來顯示處理的進度
  • 程序的運行速度可能加快
  • 在一些等待的任務(wù)實現(xiàn)上如用戶輸入、文件讀寫和網(wǎng)絡(luò)收發(fā)數(shù)據(jù)等,線程就比較有用了。在這種情況下我們可以釋放一些珍貴的資源如內(nèi)存占用等等。

線程在執(zhí)行過程中與進程還是有區(qū)別的。每個獨立的線程有一個程序運行的入口、順序執(zhí)行序列和程序的出口。但是線程不能夠獨立執(zhí)行,必須依存在應(yīng)用程序中,由應(yīng)用程序提供多個線程執(zhí)行控制。

每個線程都有他自己的一組CPU寄存器,稱為線程的上下文,該上下文反映了線程上次運行該線程的CPU寄存器的狀態(tài)。

指令指針和堆棧指針寄存器是線程上下文中兩個最重要的寄存器,線程總是在進程得到上下文中運行的,這些地址都用于標(biāo)志擁有線程的進程地址空間中的內(nèi)存。

  • 線程可以被搶占(中斷)。
  • 在其他線程正在運行時,線程可以暫時擱置(也稱為睡眠) -- 這就是線程的退讓。

?

開始學(xué)習(xí)Python線程

Python中使用線程有兩種方式:函數(shù)或者用類來包裝線程對象。

函數(shù)式:調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新線程。語法如下:

thread.start_new_thread ( function, args[, kwargs] )

參數(shù)說明:

  • function - 線程函數(shù)。
  • args - 傳遞給線程函數(shù)的參數(shù),他必須是個tuple類型。
  • kwargs - 可選參數(shù)。

實例:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

?

import thread

import time

?

# 為線程定義一個函數(shù)

def print_time( threadName, delay):

?? count = 0

?? while count <5:

????? time.sleep(delay)

????? count += 1

????? print "%s:%s" % ( threadName, time.ctime(time.time()) )

?

# 創(chuàng)建兩個線程

try:

?? thread.start_new_thread(print_time, ("Thread-1", 2, ) )

?? thread.start_new_thread(print_time, ("Thread-2", 4, ) )

except:

?? print "Error:unable to start thread"

?

while 1:

?? pass

執(zhí)行以上程序輸出結(jié)果如下:

Thread-1: Thu Jan 22 15:42:17 2009

Thread-1: Thu Jan 22 15:42:19 2009

Thread-2: Thu Jan 22 15:42:19 2009

Thread-1: Thu Jan 22 15:42:21 2009

Thread-2: Thu Jan 22 15:42:23 2009

Thread-1: Thu Jan 22 15:42:23 2009

Thread-1: Thu Jan 22 15:42:25 2009

Thread-2: Thu Jan 22 15:42:27 2009

Thread-2: Thu Jan 22 15:42:31 2009

Thread-2: Thu Jan 22 15:42:35 2009

線程的結(jié)束一般依靠線程函數(shù)的自然結(jié)束;也可以在線程函數(shù)中調(diào)用thread.exit(),他拋出SystemExit exception,達到退出線程的目的。


線程模塊

Python通過兩個標(biāo)準(zhǔn)庫thread和threading提供對線程的支持。thread提供了低級別的、原始的線程以及一個簡單的鎖。

thread 模塊提供的其他方法:

  • threading.currentThread(): 返回當(dāng)前的線程變量。
  • threading.enumerate(): 返回一個包含正在運行的線程的list。正在運行指線程啟動后、結(jié)束前,不包括啟動前和終止后的線程。
  • threading.activeCount(): 返回正在運行的線程數(shù)量,與len(threading.enumerate())有相同的結(jié)果。

除了使用方法外,線程模塊同樣提供了Thread類來處理線程,Thread類提供了以下方法:

  • run(): 用以表示線程活動的方法。
  • start():啟動線程活動。
  • join([time]): 等待至線程中止。這阻塞調(diào)用線程直至線程的join() 方法被調(diào)用中止-正常退出或者拋出未處理的異常-或者是可選的超時發(fā)生。
  • isAlive(): 返回線程是否活動的。
  • getName(): 返回線程名。
  • setName(): 設(shè)置線程名。

使用Threading模塊創(chuàng)建線程

使用Threading模塊創(chuàng)建線程,直接從threading.Thread繼承,然后重寫__init__方法和run方法:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

?

import threading

import time

?

exitFlag = 0

?

class myThread (threading.Thread):?? #繼承父類threading.Thread

??? def __init__(self,threadID, name, counter):

??????? threading.Thread.__init__(self)

??????? self.threadID= threadID

??????? self.name =name

??????? self.counter= counter

??? def run(self):?????????????????? #把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會直接運行run函數(shù)

??????? print "Starting" + self.name

????? ??print_time(self.name, self.counter, 5)

??????? print "Exiting" + self.name

?

def print_time(threadName, delay, counter):

??? while counter:

??????? if exitFlag:

??????????? thread.exit()

??????? time.sleep(delay)

??????? print "%s:%s" % (threadName, time.ctime(time.time()))

??????? counter -= 1

?

# 創(chuàng)建新線程

thread1 = myThread(1, "Thread-1", 1)

thread2 = myThread(2, "Thread-2", 2)

?

# 開啟線程

thread1.start()

thread2.start()

?

print "Exiting Main Thread"

以上程序執(zhí)行結(jié)果如下;

Starting Thread-1

Starting Thread-2

Exiting Main Thread

Thread-1: Thu Mar 21 09:10:03 2013

Thread-1: Thu Mar 21 09:10:04 2013

Thread-2: Thu Mar 21 09:10:04 2013

Thread-1: Thu Mar 21 09:10:05 2013

Thread-1: Thu Mar 21 09:10:06 2013

Thread-2: Thu Mar 21 09:10:06 2013

Thread-1: Thu Mar 21 09:10:07 2013

Exiting Thread-1

Thread-2: Thu Mar 21 09:10:08 2013

Thread-2: Thu Mar 21 09:10:10 2013

Thread-2: Thu Mar 21 09:10:12 2013

Exiting Thread-2


線程同步

如果多個線程共同對某個數(shù)據(jù)修改,則可能出現(xiàn)不可預(yù)料的結(jié)果,為了保證數(shù)據(jù)的正確性,需要對多個線程進行同步。

使用Thread對象的Lock和Rlock可以實現(xiàn)簡單的線程同步,這兩個對象都有acquire方法和release方法,對于那些需要每次只允許一個線程操作的數(shù)據(jù),可以將其操作放到acquire和release方法之間。如下:

多線程的優(yōu)勢在于可以同時運行多個任務(wù)(至少感覺起來是這樣)。但是當(dāng)線程需要共享數(shù)據(jù)時,可能存在數(shù)據(jù)不同步的問題。

考慮這樣一種情況:一個列表里所有元素都是0,線程"set"從后向前把所有元素改成1,而線程"print"負責(zé)從前往后讀取列表并打印。

那么,可能線程"set"開始改的時候,線程"print"便來打印列表了,輸出就成了一半0一半1,這就是數(shù)據(jù)的不同步。為了避免這種情況,引入了鎖的概念。

鎖有兩種狀態(tài)——鎖定和未鎖定。每當(dāng)一個線程比如"set"要訪問共享數(shù)據(jù)時,必須先獲得鎖定;如果已經(jīng)有別的線程比如"print"獲得鎖定了,那么就讓線程"set"暫停,也就是同步阻塞;等到線程"print"訪問完畢,釋放鎖以后,再讓線程"set"繼續(xù)。

經(jīng)過這樣的處理,打印列表時要么全部輸出0,要么全部輸出1,不會再出現(xiàn)一半0一半1的尷尬場面。

實例:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

?

import threading

import time

?

class myThread (threading.Thread):

??? def __init__(self,threadID, name, counter):

??????? threading.Thread.__init__(self)

??????? self.threadID= threadID

??????? self.name =name

??????? self.counter= counter

??? def run(self):

??????? print "Starting" + self.name

?????? # 獲得鎖,成功獲得鎖定后返回True

?????? # 可選的timeout參數(shù)不填時將一直阻塞直到獲得鎖定

?????? # 否則超時后將返回False

? ??????threadLock.acquire()

??????? print_time(self.name,self.counter, 3)

??????? # 釋放鎖

??????? threadLock.release()

?

def print_time(threadName, delay, counter):

??? while counter:

??????? time.sleep(delay)

??????? print "%s:%s" % (threadName, time.ctime(time.time()))

??????? counter -= 1

?

threadLock = threading.Lock()

threads = []

?

# 創(chuàng)建新線程

thread1 = myThread(1, "Thread-1", 1)

thread2 = myThread(2, "Thread-2", 2)

?

# 開啟新線程

thread1.start()

thread2.start()

?

# 添加線程到線程列表

threads.append(thread1)

threads.append(thread2)

?

# 等待所有線程完成

for t in threads:

??? t.join()

print "Exiting Main Thread"


線程優(yōu)先級隊列( Queue)

Python的Queue模塊中提供了同步的、線程安全的隊列類,包括FIFO(先入先出)隊列Queue,LIFO(后入先出)隊列 LifoQueue,和優(yōu)先級隊列PriorityQueue。這些隊列都實現(xiàn)了鎖原語,能夠在多線程中直接使用。可以使用隊列來實現(xiàn)線程間的同步。

Queue模塊中的常用方法:

  • Queue.qsize() 返回隊列的大小
  • Queue.empty() 如果隊列為空,返回True,反之False
  • Queue.full() 如果隊列滿了,返回True,反之False
  • Queue.full 與 maxsize 大小對應(yīng)
  • Queue.get([block[, timeout]])獲取隊列,timeout等待時間
  • Queue.get_nowait() 相當(dāng)Queue.get(False)
  • Queue.put(item) 寫入隊列,timeout等待時間
  • Queue.put_nowait(item) 相當(dāng)Queue.put(item, False)
  • Queue.task_done() 在完成一項工作之后,Queue.task_done()函數(shù)向任務(wù)已經(jīng)完成的隊列發(fā)送一個信號
  • Queue.join() 實際上意味著等到隊列為空,再執(zhí)行別的操作

實例:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

?

import Queue

import threading

import time

?

exitFlag = 0

?

class myThread (threading.Thread):

??? def __init__(self,threadID, name, q):

??????? threading.Thread.__init__(self)

??????? self.threadID= threadID

??????? self.name =name

??????? self.q = q

??? def run(self):

??????? print "Starting" + self.name

???????process_data(self.name, self.q)

??????? print "Exiting" + self.name

?

def process_data(threadName, q):

??? while notexitFlag:

??????? queueLock.acquire()

??????? if notworkQueue.empty():

??????????? data =q.get()

??????? ????queueLock.release()

??????????? print "%sprocessing %s" % (threadName, data)

??????? else:

???????????queueLock.release()

??????? time.sleep(1)

?

threadList = ["Thread-1", "Thread-2","Thread-3"]

nameList = ["One", "Two", "Three","Four", "Five"]

queueLock = threading.Lock()

workQueue = Queue.Queue(10)

threads = []

threadID = 1

?

# 創(chuàng)建新線程

for tName in threadList:

??? thread =myThread(threadID, tName, workQueue)

??? thread.start()

??? threads.append(thread)

??? threadID += 1

?

# 填充隊列

queueLock.acquire()

for word in nameList:

??? workQueue.put(word)

queueLock.release()

?

# 等待隊列清空

while not workQueue.empty():

??? pass

?

# 通知線程是時候退出

exitFlag = 1

?

# 等待所有線程完成

for t in threads:

??? t.join()

print "Exiting Main Thread"

以上程序執(zhí)行結(jié)果:

Starting Thread-1

Starting Thread-2

Starting Thread-3

Thread-1 processing One

Thread-2 processing Two

Thread-3 processing Three

Thread-1 processing Four

Thread-2 processing Five

Exiting Thread-3

Exiting Thread-1

Exiting Thread-2

Exiting Main Thread


出處:http://www.runoob.com/python/python-tutorial.html

總結(jié)

以上是生活随笔為你收集整理的Python基础教程(十一):多线程、XML解析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。