python中使用asyncio實(shí)現(xiàn)異步IO實(shí)例分析
1、說明
Python實(shí)現(xiàn)異步IO非常簡單,asyncio是Python 3.4版本引入的標(biāo)準(zhǔn)庫,直接內(nèi)置了對異步IO的支持。
asyncio的編程模型就是一個(gè)消息循環(huán)。我們從asyncio模塊中直接獲取一個(gè)EventLoop的引用,然后把需要執(zhí)行的協(xié)程扔到EventLoop中執(zhí)行,就實(shí)現(xiàn)了異步IO。
2、實(shí)例
import asyncio
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = yield from connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
yield from writer.drain()
while True:
line = yield from reader.readline()
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
# Ignore the body, close the socket
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
知識(shí)點(diǎn)擴(kuò)展:
數(shù)據(jù)流(Streams)
數(shù)據(jù)流(Streams)是用于處理網(wǎng)絡(luò)連接的高階異步/等待就緒(async/await-ready)原語,可以在不使用回調(diào)和底層傳輸協(xié)議的情況下發(fā)送和接收數(shù)據(jù)。
以下是一個(gè)用asyncio實(shí)現(xiàn)的TCP回顯客戶端:
import asyncio
async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8888)
print(f'Send: {message!r}')
writer.write(message.encode())
data = await reader.read(100)
print(f'Received: {data.decode()!r}')
print('Close the connection')
writer.close()
await writer.wait_closed()
asyncio.run(tcp_echo_client('Hello World!'))
到此這篇關(guān)于python中使用asyncio實(shí)現(xiàn)異步IO實(shí)例分析的文章就介紹到這了,更多相關(guān)python中使用asyncio實(shí)現(xiàn)異步IO內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于python實(shí)現(xiàn)監(jiān)聽Rabbitmq系統(tǒng)日志代碼示例
這篇文章主要介紹了基于python實(shí)現(xiàn)監(jiān)聽Rabbitmq系統(tǒng)日志代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
python實(shí)現(xiàn)ROA算子邊緣檢測算法
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)ROA算子邊緣檢測算法,以光學(xué)圖像為例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-04-04
python實(shí)現(xiàn)IOU計(jì)算案例
這篇文章主要介紹了python實(shí)現(xiàn)IOU計(jì)算案例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Keras搭建孿生神經(jīng)網(wǎng)絡(luò)Siamese?network比較圖片相似性
這篇文章主要為大家介紹了Keras搭建孿生神經(jīng)網(wǎng)絡(luò)Siamese?network比較圖片相似性,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Python+selenium實(shí)現(xiàn)瀏覽器基本操作詳解
這篇文章主要為大家詳細(xì)介紹了如何通過python腳本實(shí)現(xiàn)瀏覽器的一些基本操作,如:瀏覽器的前進(jìn)后退、頁面刷新等,感興趣的可以學(xué)習(xí)一下2022-06-06
python按行讀取文件,去掉每行的換行符\n的實(shí)例
下面小編就為大家分享一篇python按行讀取文件,去掉每行的換行符\n的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
python如何使用正則表達(dá)式的前向、后向搜索及前向搜索否定模式詳解
這篇文章主要給大家介紹了關(guān)于python如何使用正則表達(dá)式的前向、后向搜索及前向搜索否定模式的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。2017-11-11

