python asyncio 協(xié)程庫(kù)的使用
asyncio 是 python 力推多年的攜程庫(kù),與其 線程庫(kù) 相得益彰,更輕量,并且協(xié)程可以訪問(wèn)同一進(jìn)程中的變量,不需要進(jìn)程間通信來(lái)傳遞數(shù)據(jù),所以使用起來(lái)非常順手。
asyncio 官方文檔寫的非常簡(jiǎn)練和有效,半小時(shí)內(nèi)可以學(xué)習(xí)和測(cè)試完,下面為我的一段 HelloWrold,感覺(jué)可以更快速的幫你認(rèn)識(shí) 協(xié)程 。
定義協(xié)程
import asyncio import time async def say_after(delay, what): await asyncio.sleep(delay) print(what)
async 關(guān)鍵字用來(lái)聲明一個(gè)協(xié)程函數(shù),這種函數(shù)不能直接調(diào)用,會(huì)拋出異常。正確的調(diào)用姿勢(shì)有:
await 協(xié)程() await asyncio.gather(協(xié)程1(), 協(xié)程2()) await asyncio.waite([協(xié)程1(), 協(xié)程2()]) asyncio.create_task(協(xié)程())
await 阻塞式調(diào)用協(xié)程
先來(lái)測(cè)試前 3 種 await 的方式:
async def main1(): # 直接 await,順序執(zhí)行 await say_after(2, "2s") await say_after(1, "1s") async def main2(): # 使用 gather,并發(fā)執(zhí)行 await asyncio.gather(say_after(2, "2s"), say_after(1, "1s")) async def main3(): # 使用 wait,簡(jiǎn)單等待 # 3.8 版后已廢棄: 如果 aws 中的某個(gè)可等待對(duì)象為協(xié)程,它將自動(dòng)作為任務(wù)加入日程。直接向 wait() 傳入?yún)f(xié)程對(duì)象已棄用,因?yàn)檫@會(huì)導(dǎo)致 令人迷惑的行為。 # 3.10 版后移除 await asyncio.wait([say_after(2, "2s"), say_after(1, "1s")])
python 規(guī)定: 調(diào)用協(xié)程可以用 await,但 await 必須在另一個(gè)協(xié)程中 —— 這不死循環(huán)了?不會(huì)的,asyncio 提供了多個(gè)能夠最初調(diào)用協(xié)程的入口:
asyncio.get_event_loop().run_until_complete(協(xié)程) asyncio.run(協(xié)程)
封裝一個(gè)計(jì)算時(shí)間的函數(shù),然后把 2 種方式都試一下:
def runtime(entry, func):
print("-" * 10 + func.__name__)
start = time.perf_counter()
entry(func())
print("=" * 10 + "{:.5f}".format(time.perf_counter() - start))
print("########### 用 loop 入口協(xié)程 ###########")
loop = asyncio.get_event_loop()
runtime(loop.run_until_complete, main1)
runtime(loop.run_until_complete, main2)
runtime(loop.run_until_complete, main3)
loop.close()
print("########### 用 run 入口協(xié)程 ###########")
runtime(asyncio.run, main1)
runtime(asyncio.run, main2)
runtime(asyncio.run, main3)
運(yùn)行結(jié)果:
########### 用 loop 入口協(xié)程 ########### ----------main1 2s 1s ==========3.00923 ----------main2 1s 2s ==========2.00600 ----------main3 1s 2s ==========2.00612 ########### 用 run 入口協(xié)程 ########### ----------main1 2s 1s ==========3.01193 ----------main2 1s 2s ==========2.00681 ----------main3 1s 2s ==========2.00592
可見(jiàn),2 種協(xié)程入口調(diào)用方式差別不大
下面,需要明確 2 個(gè)問(wèn)題:
協(xié)程間的并發(fā)問(wèn)題 :除了 main1 耗時(shí) 3s 外,其他都是 2s,說(shuō)明 main1 方式串行執(zhí)行 2 個(gè)協(xié)程,其他是并發(fā)執(zhí)行協(xié)程。
協(xié)程是否阻塞父協(xié)程/父進(jìn)程的問(wèn)題 :上述測(cè)試都使用了 await,即等待協(xié)程執(zhí)行完畢后再繼續(xù)往下走,所以都是阻塞式的,主進(jìn)程都在此等待協(xié)程的執(zhí)行完?!?那么如何才能不阻塞父協(xié)程呢? 不加 await 行么? —— 上面 3 種方式都不行!
下面介紹可以不阻塞主協(xié)程的方式。
task 實(shí)現(xiàn)更靈活的協(xié)程
一切都在代碼中:
# 驗(yàn)證 task 啟動(dòng)協(xié)程是立即執(zhí)行的
async def main4():
# create_task() Python 3.7 中被加入
task1 = asyncio.create_task(say_after(2, "2s"))
task2 = asyncio.create_task(say_after(1, "1s"))
# 創(chuàng)建任務(wù)后會(huì)立即開(kāi)始執(zhí)行,后續(xù)可以用 await 來(lái)等待其完成后再繼續(xù),也可以被 cancle
await task1 # 等待 task1 執(zhí)行完,其實(shí)返回時(shí) 2 個(gè)task 都已經(jīng)執(zhí)行完
print("--") # 最后才會(huì)被打印,因?yàn)?2 個(gè)task 都已經(jīng)執(zhí)行完
await task2
# 這里是等待所有 task 結(jié)束才繼續(xù)運(yùn)行。
# 驗(yàn)證父協(xié)程與子協(xié)程的關(guān)閉關(guān)系
async def main5():
task1 = asyncio.create_task(say_after(2, "2s"))
task2 = asyncio.create_task(say_after(1, "1s"))
# 如果不等待,函數(shù)會(huì)直接 return,main5 協(xié)程結(jié)束,task1/2 子協(xié)程也結(jié)束,所以看不到打印
# 此處等待 1s,則會(huì)只看到 1 個(gè),等待 >2s,則會(huì)看到 2 個(gè) task 的打印
await asyncio.sleep(2)
# python3.8 后 python 為 asyncio 的 task 增加了很多功能:
# get/set name、獲取正在運(yùn)行的 task、cancel 功能
# 驗(yàn)證 task 的 cancel() 功能
async def cancel_me(t):
# 定義一個(gè)可處理 CancelledError 的協(xié)程
print("cancel_me(): before sleep")
try:
await asyncio.sleep(t)
except asyncio.CancelledError:
print("cancel_me(): cancel sleep")
raise
finally:
print("cancel_me(): after sleep")
return "I hate be canceled"
async def main6():
async def test(t1, t2):
task = asyncio.create_task(cancel_me(t1))
await asyncio.sleep(t2)
task.cancel() # 會(huì)在 task 內(nèi)引發(fā)一個(gè) CancelledError
try:
await task
except asyncio.CancelledError:
print("main(): cancel_me is cancelled now")
try:
print(task.result())
except asyncio.CancelledError:
print("main(): cancel_me is cancelled now")
# 讓其運(yùn)行2s,但在1s時(shí) cancel 它
await test(2, 1) # await 和 result 時(shí)都會(huì)引發(fā) CancelledError
await test(1, 2) # await 和 result 時(shí)不會(huì)引發(fā),并且 result 會(huì)得到函數(shù)的返回值
runtime(asyncio.run, main4)
runtime(asyncio.run, main5)
runtime(asyncio.run, main6)
運(yùn)行結(jié)果:
----------main4 1s 2s -- ==========2.00557 ----------main5 1s 2s ==========3.00160 ----------main6 cancel_me(): before sleep cancel_me(): cancel sleep cancel_me(): after sleep main(): cancel_me is cancelled now main(): cancel_me is cancelled now cancel_me(): before sleep cancel_me(): after sleep I hate be canceled ==========3.00924
技術(shù)總結(jié)
細(xì)節(jié)都在注釋里直接描述了,總結(jié)一下:
- await 會(huì)阻塞主協(xié)程,等待子協(xié)程完成
- await asyncio.gather/wait() 可以實(shí)現(xiàn)多個(gè)子協(xié)程的并發(fā)執(zhí)行
- await 本身要在協(xié)程中執(zhí)行,即在父協(xié)程中執(zhí)行
- asyncio.get_event_loop().run_until_complete() 和 asyncio.run() 可作為最初的協(xié)程開(kāi)始入口
- task 是最新、最推薦的協(xié)程方式,可以完成阻塞、非阻塞,
- task = asyncio.create_task(協(xié)程) 后直接開(kāi)始執(zhí)行了,并不會(huì)等待其他指令
- await task 是阻塞式,等待 task 執(zhí)行結(jié)束
- 不 await,非阻塞,但要此時(shí)父協(xié)程不能退出,否則 task 作為子協(xié)程也被退出
- task 可 cancel() 取消功能,可 result() 獲取子協(xié)程的返回值
以上就是python asyncio 協(xié)程庫(kù)的使用的詳細(xì)內(nèi)容,更多關(guān)于python asyncio 協(xié)程庫(kù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
django 實(shí)現(xiàn)電子支付功能的示例代碼
這篇文章主要介紹了django 實(shí)現(xiàn)電子支付功能的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-07-07
詳解Python實(shí)現(xiàn)多進(jìn)程異步事件驅(qū)動(dòng)引擎
本篇文章主要介紹了詳解Python實(shí)現(xiàn)多進(jìn)程異步事件驅(qū)動(dòng)引擎,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
使用Python爬蟲框架獲取HTML網(wǎng)頁(yè)中指定區(qū)域的數(shù)據(jù)
在當(dāng)今互聯(lián)網(wǎng)時(shí)代,數(shù)據(jù)已經(jīng)成為了一種寶貴的資源,無(wú)論是進(jìn)行市場(chǎng)分析、輿情監(jiān)控,還是進(jìn)行學(xué)術(shù)研究,獲取網(wǎng)頁(yè)中的數(shù)據(jù)都是一個(gè)非常重要的步驟,Python提供了多種爬蟲框架來(lái)幫助我們高效地獲取網(wǎng)頁(yè)數(shù)據(jù),本文將詳細(xì)介紹如何使用Python爬蟲框架來(lái)獲取HTML網(wǎng)頁(yè)中指定區(qū)域的數(shù)據(jù)2025-03-03
對(duì)PyQt5中樹結(jié)構(gòu)的實(shí)現(xiàn)方法詳解
今天小編就為大家分享一篇對(duì)PyQt5中樹結(jié)構(gòu)的實(shí)現(xiàn)方法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06
解決每次打開(kāi)pycharm直接進(jìn)入項(xiàng)目的問(wèn)題
今天小編就為大家分享一篇解決每次打開(kāi)pycharm直接進(jìn)入項(xiàng)目的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
django中模板的html自動(dòng)轉(zhuǎn)意方法
今天小編就為大家分享一篇django中模板的html自動(dòng)轉(zhuǎn)意方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
Python功能點(diǎn)實(shí)現(xiàn):函數(shù)級(jí)/代碼塊級(jí)計(jì)時(shí)器
今天小編就為大家分享一篇關(guān)于Python功能點(diǎn)實(shí)現(xiàn):函數(shù)級(jí)/代碼塊級(jí)計(jì)時(shí)器,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01
Python給對(duì)象數(shù)組排序的方法實(shí)現(xiàn)
本文主要介紹了Python給對(duì)象數(shù)組排序的方法實(shí)現(xiàn),可以使用sorted()函數(shù)或list.sort()方法來(lái)對(duì)對(duì)象數(shù)組按照第二個(gè)值進(jìn)行排序,具有一定的參考價(jià)值,感興趣的可以了解一下2025-03-03
Python實(shí)現(xiàn)自動(dòng)訪問(wèn)網(wǎng)頁(yè)的例子
今天小編就為大家分享一篇Python實(shí)現(xiàn)自動(dòng)訪問(wèn)網(wǎng)頁(yè)的例子,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
python 監(jiān)控服務(wù)器是否有人遠(yuǎn)程登錄(詳細(xì)思路+代碼)
這篇文章主要介紹了python 監(jiān)控服務(wù)器是否有人遠(yuǎn)程登錄的方法,幫助大家利用python 監(jiān)控服務(wù)器,感興趣的朋友可以了解下2020-12-12

