Python使用asyncio處理異步編程的代碼示例
在 Python 中,異步編程可以使用 asyncio
庫,該庫提供了一些工具和功能來編寫異步代碼。以下是處理異步編程的幾個(gè)關(guān)鍵概念和示例。
關(guān)鍵概念
- 異步函數(shù)(coroutine):使用
async def
定義的函數(shù)。 - 等待(await):在異步函數(shù)內(nèi)部使用
await
關(guān)鍵字等待一個(gè)異步操作完成。 - 事件循環(huán)(event loop):異步操作的調(diào)度器,管理所有的異步任務(wù)和回調(diào)。
- 任務(wù)(task):由事件循環(huán)調(diào)度執(zhí)行的協(xié)程。
基本示例
以下是一個(gè)簡單的異步函數(shù)示例:
import asyncio async def say_hello(): print("Hello") await asyncio.sleep(1) print("World") # 獲取事件循環(huán)并運(yùn)行異步函數(shù) asyncio.run(say_hello())
在這個(gè)示例中,say_hello
是一個(gè)異步函數(shù),它在打印 “Hello” 后等待一秒鐘,然后打印 “World”。
并發(fā)執(zhí)行多個(gè)異步函數(shù)
可以使用 asyncio.gather
并發(fā)執(zhí)行多個(gè)異步函數(shù):
import asyncio async def say_after(delay, message): await asyncio.sleep(delay) print(message) async def main(): task1 = asyncio.create_task(say_after(1, "Hello")) task2 = asyncio.create_task(say_after(2, "World")) await task1 await task2 asyncio.run(main())
在這個(gè)示例中,main
函數(shù)創(chuàng)建了兩個(gè)任務(wù) task1
和 task2
,并發(fā)執(zhí)行它們。say_after
函數(shù)等待指定的時(shí)間后打印消息。
異步 I/O 操作
異步編程特別適用于 I/O 密集型任務(wù),如網(wǎng)絡(luò)請求。以下是一個(gè)使用 aiohttp
庫進(jìn)行異步 HTTP 請求的示例:
import aiohttp import asyncio async def fetch(url): async with aiohttp.ClientSession() as session: async with session.get(url) as response: return await response.text() async def main(): url = 'https://www.example.com' html = await fetch(url) print(html) asyncio.run(main())
在這個(gè)示例中,fetch
函數(shù)使用 aiohttp
庫進(jìn)行異步 HTTP 請求,main
函數(shù)調(diào)用 fetch
并打印響應(yīng)內(nèi)容。
超時(shí)處理
可以使用 asyncio.wait_for
設(shè)置超時(shí):
import asyncio async def say_hello(): await asyncio.sleep(2) return "Hello, World!" async def main(): try: result = await asyncio.wait_for(say_hello(), timeout=1) print(result) except asyncio.TimeoutError: print("The coroutine took too long to complete") asyncio.run(main())
在這個(gè)示例中,如果 say_hello
函數(shù)在 1 秒內(nèi)沒有完成,將會引發(fā) asyncio.TimeoutError
。
異步上下文管理器和迭代器
可以使用 async with
和 async for
處理異步上下文管理器和迭代器:
import aiohttp import asyncio class AsyncContextManager: async def __aenter__(self): print("Entering context") return self async def __aexit__(self, exc_type, exc, tb): print("Exiting context") async def do_something(self): await asyncio.sleep(1) print("Doing something") async def main(): async with AsyncContextManager() as manager: await manager.do_something() asyncio.run(main())
在這個(gè)示例中,AsyncContextManager
類實(shí)現(xiàn)了異步上下文管理協(xié)議。main
函數(shù)使用 async with
進(jìn)入和退出上下文,并調(diào)用異步方法 do_something
。
小結(jié)
通過使用 asyncio
庫,Python 提供了一種強(qiáng)大且靈活的方式來處理異步編程。異步編程可以顯著提高 I/O 密集型任務(wù)的性能,使得代碼在處理多個(gè)任務(wù)時(shí)更加高效。掌握異步編程的基本概念和工具將有助于你編寫高性能的異步應(yīng)用程序。
以上就是Python使用asyncio處理異步編程的代碼示例的詳細(xì)內(nèi)容,更多關(guān)于Python處理異步編程的資料請關(guān)注腳本之家其它相關(guān)文章!
- Python使用asyncio實(shí)現(xiàn)異步操作的示例
- Python中asyncio的多種用法舉例(異步同步)
- Python使用asyncio包實(shí)現(xiàn)異步編程方式
- Python異步庫asyncio、aiohttp詳解
- python協(xié)程異步IO中asyncio的使用
- Python使用asyncio標(biāo)準(zhǔn)庫對異步IO的支持
- Python協(xié)程異步爬取數(shù)據(jù)(asyncio+aiohttp)實(shí)例
- Python使用asyncio異步時(shí)的常見問題總結(jié)
- Python asyncio異步編程常見問題小結(jié)
- Python asyncio異步編程簡單實(shí)現(xiàn)示例
- Python中asyncio庫實(shí)現(xiàn)異步編程的示例
相關(guān)文章
python中itertools模塊zip_longest函數(shù)詳解
itertools模塊包含創(chuàng)建高效迭代器的函數(shù),這些函數(shù)的返回值不是list,而是iterator(可迭代對象),可以用各種方式對數(shù)據(jù)執(zhí)行循環(huán)操作,今天我們來詳細(xì)探討下zip_longest函數(shù)2018-06-0620行Python代碼實(shí)現(xiàn)視頻字符化功能
這篇文章主要介紹了20行Python代碼實(shí)現(xiàn)視頻字符化功能,本文通過實(shí)例代碼截圖的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-04-04Python開發(fā)常用五種循環(huán)方式的場景性能比較
Python是一門高級編程語言,其擁有多種循環(huán)方式,如for循環(huán)、while循環(huán)、do-while循環(huán)等。本文將逐個(gè)分析Python所有的循環(huán)執(zhí)行效率和適用場景,需要的可以參考一下2023-04-04pandas使用get_dummies進(jìn)行one-hot編碼的方法
今天小編就為大家分享一篇pandas使用get_dummies進(jìn)行one-hot編碼的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07