国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

python中使用asyncio實現異步IO實例分析

瀏覽:24日期:2022-06-27 09:47:21
1、說明

Python實現異步IO非常簡單,asyncio是Python 3.4版本引入的標準庫,直接內置了對異步IO的支持。

asyncio的編程模型就是一個消息循環。我們從asyncio模塊中直接獲取一個EventLoop的引用,然后把需要執行的協程扔到EventLoop中執行,就實現了異步IO。

2、實例

import asyncio@asyncio.coroutinedef wget(host): print(’wget %s...’ % host) connect = asyncio.open_connection(host, 80) reader, writer = yield from connect header = ’GET / HTTP/1.0rnHost: %srnrn’ % host writer.write(header.encode(’utf-8’)) yield from writer.drain() while True: line = yield from reader.readline() if line == b’rn’: 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()

知識點擴展:

數據流(Streams)

數據流(Streams)是用于處理網絡連接的高階異步/等待就緒(async/await-ready)原語,可以在不使用回調和底層傳輸協議的情況下發送和接收數據。

以下是一個用asyncio實現的TCP回顯客戶端:

import asyncioasync 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!’))

到此這篇關于python中使用asyncio實現異步IO實例分析的文章就介紹到這了,更多相關python中使用asyncio實現異步IO內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 黎城县| 桂阳县| 乌苏市| 巴南区| 连山| 德阳市| 镇雄县| 巧家县| 十堰市| 平远县| 永康市| 本溪市| 邯郸县| 闽侯县| 乾安县| 西乌珠穆沁旗| 雷州市| 贵德县| 视频| 南江县| 崇信县| 大荔县| 西华县| 玉林市| 平度市| 郁南县| 定日县| 盐源县| 通化市| 济南市| 宝坻区| 兴义市| 枞阳县| 高邑县| 甘肃省| 谢通门县| 海阳市| 砚山县| 鄯善县| 大连市| 阿克苏市|