1. 程式人生 > >學習筆記-Python基礎18-asyncio非同步

學習筆記-Python基礎18-asyncio非同步

# asyncio
  - Python3.4開始引入標準庫當中,內建對非同步io的支援
  - asyncio本身是一個訊息迴圈
  - 步驟:
    - 1、建立訊息迴圈
    - 2、把協成加進去
    - 3、關閉

# asyncio非同步協成,簡單案例1
import threading
import asyncio

@asyncio.coroutine
# 使用協成
def hello():
    print('Hello world! (%s)' % threading.currentThread())
    print('Start...(%s)' % threading.currentThread())
    
yield from asyncio.sleep(5) print('Done...(%s)' % threading.currentThread()) print('Hello again! (%s)' % threading.currentThread()) # 啟動訊息迴圈 loop = asyncio.get_event_loop() # 定義任務 tasks = [hello(), hello()] # asyncio使用wait等待tasks執行完畢 loop.run_until_complete(asyncio.wait(tasks)) # 關閉訊息尋混 loop.close()
''' Hello world! (<_MainThread(MainThread, started 9272)>) Start...(<_MainThread(MainThread, started 9272)>) Hello world! (<_MainThread(MainThread, started 9272)>) Start...(<_MainThread(MainThread, started 9272)>) Done...(<_MainThread(MainThread, started 9272)>) Hello again! (<_MainThread(MainThread, started 9272)>) Done...(<_MainThread(MainThread, started 9272)>) Hello again! (<_MainThread(MainThread, started 9272)>)
''' # asyncio非同步用協成請求網路地址,案例2 import asyncio @asyncio.coroutine def wget(host): print('weget %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.writer(header.encode('utf-8')) yield from writer.drain() while True: line = yield from reader.readline() # http協議的換行使用\r\n if line ==b'\r\n': break print('%s header > %s' % (host, line.decode('utf-8').rstrip())) writer.close() loop = asyncio.get_event_loop() tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com']] loop.run_until_complete(asyncio.wait(tasks)) loop.close() ''' weget www.sina.com.cn... weget www.sohu.com... '''

 

# asyncio and await
  - 為了更好的表示非同步io
  - Python3.5引入
  - 讓協成程式碼更簡潔
  - 使用上,可以簡單的進行替換
    - 用asyncio替換@asyncio.coroutine
    - 用await替換yield from