Python 3.5 及更高版本引入了關(guān)于異步操作的原生支持,主要包括 async 和 await 兩個(gè)關(guān)鍵字,以及 asyncio 模塊。
這種異步操作的主要思想是協(xié)程 (coroutine)。一個(gè)協(xié)程可以在某些點(diǎn)上暫停執行,以便其他協(xié)程可以運行。
這里有一個(gè)使用 asyncio 進(jìn)行異步操作的基本示例:
import asyncioasync def my_coroutine(): await asyncio.sleep(1) # 休眠 1 秒 print('Hello')# Python 3.7 及以上版本可以直接使用 asyncio.run()asyncio.run(my_coroutine())在這個(gè)示例中,my_coroutine 是一個(gè)協(xié)程。它使用 await 關(guān)鍵字暫停自己的執行,等待 asyncio.sleep(1) 完成。在這個(gè)時(shí)候,其他協(xié)程可以執行。當 asyncio.sleep(1) 完成后,my_coroutine 繼續執行,打印 'Hello'。
你也可以同時(shí)運行多個(gè)協(xié)程。這里有個(gè)例子:
import asyncioasync def print_after(wait_time, msg): await asyncio.sleep(wait_time) print(msg)# Python 3.7 及以上版本可以直接使用 asyncio.run()asyncio.run(print_after(1, 'Hello'))asyncio.run(print_after(2, 'World'))這個(gè)程序將首先打印 'Hello',然后等待一秒后打印 'World'。
你還可以使用 asyncio.gather 來(lái)并行運行多個(gè)協(xié)程:
import asyncioasync def print_after(wait_time, msg): await asyncio.sleep(wait_time) print(msg)# Python 3.7 及以上版本可以直接使用 asyncio.run()asyncio.run(asyncio.gather(print_after(1, 'Hello'), print_after(2, 'World')))在這個(gè)示例中,print_after(1, 'Hello') 和 print_after(2, 'World') 將并行運行。由于 'Hello' 的等待時(shí)間更短,它將首先打印,然后等待一秒后打印 'World'。
注意,這只是 Python 中異步操作的基本示例。實(shí)際上,asyncio 庫提供了許多高級特性,例如事件循環(huán)、任務(wù)、Futures、信號量、隊列等,可以滿(mǎn)足更復雜的異步編程需求。
聯(lián)系客服