婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > python中使用asyncio實現異步IO實例分析

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

熱門標簽:遼寧智能外呼系統需要多少錢 阿里電話機器人對話 qt百度地圖標注 螳螂科技外呼系統怎么用 正安縣地圖標注app 電銷機器人系統廠家鄭州 地圖地圖標注有嘆號 舉辦過冬奧會的城市地圖標注 400電話申請資格

1、說明

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

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

2、實例

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()

知識點擴展:

數據流(Streams)

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

以下是一個用asyncio實現的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!'))

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

您可能感興趣的文章:
  • Python 異步協程函數原理及實例詳解
  • Python異步編程之協程任務的調度操作實例分析
  • python中asyncio異步編程學習
  • Python協程asyncio異步編程筆記分享

標簽:淘寶好評回訪 信陽 隨州 濟源 合肥 阜新 興安盟 昭通

巨人網絡通訊聲明:本文標題《python中使用asyncio實現異步IO實例分析》,本文關鍵詞  python,中,使用,asyncio,實現,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《python中使用asyncio實現異步IO實例分析》相關的同類信息!
  • 本頁收集關于python中使用asyncio實現異步IO實例分析的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 龙海市| 崇礼县| 云浮市| 新宾| 准格尔旗| 太白县| 建宁县| 隆昌县| 宁南县| 文成县| 西宁市| 远安县| 白山市| 墨玉县| 沙坪坝区| 香港| 宜兰市| 莆田市| 河西区| 甘肃省| 南陵县| 永济市| 乌鲁木齐市| 陈巴尔虎旗| 洪湖市| 墨脱县| 秭归县| 利川市| 花垣县| 运城市| 安龙县| 开封市| 洪湖市| 乐都县| 招远市| 屯门区| 梁平县| 桐柏县| 肥城市| 威远县| 宝兴县|