濮阳杆衣贸易有限公司

主頁 > 知識庫 > python中使用asyncio實現(xiàn)異步IO實例分析

python中使用asyncio實現(xiàn)異步IO實例分析

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

1、說明

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

asyncio的編程模型就是一個消息循環(huán)。我們從asyncio模塊中直接獲取一個EventLoop的引用,然后把需要執(zhí)行的協(xié)程扔到EventLoop中執(zhí)行,就實現(xiàn)了異步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()

知識點擴展:

數(shù)據(jù)流(Streams)

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

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

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

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

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

巨人網(wǎng)絡通訊聲明:本文標題《python中使用asyncio實現(xiàn)異步IO實例分析》,本文關鍵詞  python,中,使用,asyncio,實現(xiàn),;如發(fā)現(xiàn)本文內(nèi)容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《python中使用asyncio實現(xiàn)異步IO實例分析》相關的同類信息!
  • 本頁收集關于python中使用asyncio實現(xiàn)異步IO實例分析的相關信息資訊供網(wǎng)民參考!
  • 推薦文章
    安顺市| 大方县| 南川市| 贡嘎县| 绥德县| 香河县| 新宾| 内乡县| 肃南| 津市市| 六盘水市| 安义县| 荣昌县| 专栏| 台东市| 松阳县| 当雄县| 靖州| 锡林浩特市| 大姚县| 南涧| 芮城县| 东港市| 宣城市| 社旗县| 清水县| 沁源县| 玉龙| 长泰县| 峨眉山市| 吴川市| 仙游县| 花莲县| 株洲市| 板桥市| 郁南县| 集安市| 泽普县| 巢湖市| 电白县| 海南省|