Python 中的 async await 概念(實例)(ValueError: too many file descriptors in select())

代碼實例

async def get_screenhot(demo):
    await func1()
    await func2()
    await func3()

def test():
    new_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(new_loop)
    title, screenhot = asyncio.get_event_loop().run_until_complete(get_screenhot(demo))

test()

原作者實例 

from time import sleep, time


def demo1():
    """
    假設我們有三臺洗衣機, 現在有三批衣服需要分別放到這三臺洗衣機裏面洗.
    """
    
    def washing1():
        sleep(3)  # 第一臺洗衣機, 需要洗3秒才能洗完 (只是打個比方)
        print('washer1 finished')  # 洗完的時候, 洗衣機會響一下, 告訴我們洗完了
    
    def washing2():
        sleep(2)
        print('washer2 finished')
    
    def washing3():
        sleep(5)
        print('washer3 finished')
    
    washing1()
    washing2()
    washing3()
    
    """
    這個還是很容易理解的, 運行 demo1(), 那麼需要10秒鐘才能把全部衣服洗完.
    沒錯, 大部分時間都花在挨個地等洗衣機上了.
    """


def demo2():
    """
    現在我們想要避免無謂的等待, 爲了提高效率, 我們將使用 async.
    washing1/2/3() 本是 "普通函數", 現在我們用 async 把它們升級爲 "異步函數".
    
    注: 一個異步的函數, 有個更標準的稱呼, 我們叫它 "協程" (coroutine).
    """
    
    async def washing1():
        sleep(3)
        print('washer1 finished')
    
    async def washing2():
        sleep(2)
        print('washer2 finished')
    
    async def washing3():
        sleep(5)
        print('washer3 finished')
    
    washing1()
    washing2()
    washing3()
    
    """
    從正常人的理解來看, 我們現在有了異步函數, 但是卻忘了定義應該什麼時候 "離開" 一臺洗衣
    機, 去看看另一個... 這就會導致, 現在的情況是我們一邊看着第一臺洗衣機, 一邊着急地想着
    "是不是該去開第二臺洗衣機了呢?" 但又不敢去 (只是打個比方), 最終還是花了10秒的時間才
    把衣服洗完.
    
    PS: 其實 demo2() 是無法運行的, Python 會直接警告你:
        RuntimeWarning: coroutine 'demo2.<locals>.washing1' was never awaited
        RuntimeWarning: coroutine 'demo2.<locals>.washing2' was never awaited
        RuntimeWarning: coroutine 'demo2.<locals>.washing3' was never awaited
    """


def demo3():
    """
    現在我們吸取了上次的教訓, 告訴自己洗衣服的過程是 "可等待的" (awaitable), 在它開始洗衣服
    的時候, 我們可以去弄別的機器.
    """
    
    async def washing1():
        await sleep(3)  # 注意這裏加入了 await
        print('washer1 finished')
    
    async def washing2():
        await sleep(2)
        print('washer2 finished')
    
    async def washing3():
        await sleep(5)
        print('washer3 finished')
    
    washing1()
    washing2()
    washing3()
    
    """
    嘗試運行一下, 我們會發現還是會報錯 (報錯內容和 demo2 一樣). 這裏我說一下原因, 以及在
    demo4 中會給出一個最終答案:
        1. 第一個問題是, await 後面必須跟一個 awaitable 類型或者具有 __await__ 屬性的
        對象. 這個 awaitable, 並不是我們認爲 sleep() 是 awaitable 就可以 await 了,
        常見的 awaitable 對象應該是:
            await asyncio.sleep(3)  # asyncio 庫的 sleep() 機制與 time.sleep() 不
            # 同, 前者是 "假性睡眠", 後者是會導致線程阻塞的 "真性睡眠"
            await an_async_function()  # 一個異步的函數, 也是可等待的對象
        以下是不可等待的:
            await time.sleep(3)
            x = await 'hello'  # <class 'str'> doesn't define '__await__'
            x = await 3 + 2  # <class 'int'> dosen't define '__await__'
            x = await None  # ...
            x = await a_sync_function()  # 普通的函數, 是不可等待的
            
        2. 第二個問題是, 如果我們要執行異步函數, 不能用這樣的調用方法:
            washing1()
            washing2()
            washing3()
        而應該用 asyncio 庫中的事件循環機制來啓動 (具體見 demo4 講解).
    """


def demo4():
    """
    這是最終我們想要的實現.
    """
    import asyncio  # 引入 asyncio 庫
    
    async def washing1():
        await asyncio.sleep(3)  # 使用 asyncio.sleep(), 它返回的是一個可等待的對象
        print('washer1 finished')
    
    async def washing2():
        await asyncio.sleep(2)
        print('washer2 finished')
    
    async def washing3():
        await asyncio.sleep(5)
        print('washer3 finished')
    
    """
    事件循環機制分爲以下幾步驟:
        1. 創建一個事件循環
        2. 將異步函數加入事件隊列
        3. 執行事件隊列, 直到最晚的一個事件被處理完畢後結束
        4. 最後建議用 close() 方法關閉事件循環, 以徹底清理 loop 對象防止誤用
    """
    # 1. 創建一個事件循環
    loop = asyncio.get_event_loop()
    
    # 2. 將異步函數加入事件隊列
    tasks = [
        washing1(),
        washing2(),
        washing3(),
    ]
    
    # 3. 執行事件隊列, 直到最晚的一個事件被處理完畢後結束
    loop.run_until_complete(asyncio.wait(tasks))
    """
    PS: 如果不滿意想要 "多洗幾遍", 可以多寫幾句:
        loop.run_until_complete(asyncio.wait(tasks))
        loop.run_until_complete(asyncio.wait(tasks))
        loop.run_until_complete(asyncio.wait(tasks))
        ...
    """
    
    # 4. 如果不再使用 loop, 建議養成良好關閉的習慣
    # (有點類似於文件讀寫結束時的 close() 操作)
    loop.close()
    
    """
    最終的打印效果:
        washer2 finished
        washer1 finished
        washer3 finished
        elapsed time = 5.126561641693115
        	(畢竟切換線程也要有點耗時的)
        
    說句題外話, 我看有的博主的加入事件隊列是這樣寫的:
        tasks = [
            loop.create_task(washing1()),
            loop.create_task(washing2()),
            loop.create_task(washing3()),
        ]
        運行的效果是一樣的, 暫不清楚爲什麼他們這樣做.
    """


if __name__ == '__main__':
    # 爲驗證是否真的縮短了時間, 我們計個時
    start = time()
    
    # demo1()  # 需花費10秒
    # demo2()  # 會報錯: RuntimeWarning: coroutine ... was never awaited
    # demo3()  # 會報錯: RuntimeWarning: coroutine ... was never awaited
    demo4()  # 需花費5秒多一點點
    
    end = time()
    print('elapsed time = ' + str(end - start))

 

其他文章:python異步編程之asyncio(百萬併發)

 

一、asyncio

下面通過舉例來對比同步代碼和異步代碼編寫方面的差異,其次看下兩者性能上的差距,我們使用sleep(1)模擬耗時1秒的io操作。

 ·同步代碼

import time

def hello():
    time.sleep(1)

def run():
    for i in range(5):
        hello()
        print('Hello World:%s' % time.time())  # 任何偉大的代碼都是從Hello World 開始的!
if __name__ == '__main__':
    run()

輸出:(間隔約是1s)

Hello World:1527595175.4728756
Hello World:1527595176.473001
Hello World:1527595177.473494
Hello World:1527595178.4739306
Hello World:1527595179.474482

·異步代碼

import time
import asyncio

# 定義異步函數
async def hello():
    asyncio.sleep(1)
    print('Hello World:%s' % time.time())

def run():
    for i in range(5):
        loop.run_until_complete(hello())

loop = asyncio.get_event_loop()
if __name__ =='__main__':
    run()

 輸出:

Hello World:1527595104.8338501
Hello World:1527595104.8338501
Hello World:1527595104.8338501
Hello World:1527595104.8338501
Hello World:1527595104.8338501
async def 用來定義異步函數,其內部有異步操作。每個線程有一個事件循環,主線程調用asyncio.get_event_loop()時會創建事件循環,你需要把異步的任務丟給這個循環的run_until_complete()方法,事件循環會安排協同程序的執行。=

二、aiohttp

  如果需要併發http請求怎麼辦呢,通常是用requests,但requests是同步的庫,如果想異步的話需要引入aiohttp。這裏引入一個類,from aiohttp import ClientSession,首先要建立一個session對象,然後用session對象去打開網頁。session可以進行多項操作,比如post, get, put, head等。

基本用法:

async with ClientSession() as session:
    async with session.get(url) as response:

aiohttp異步實現的例子:

import asyncio
from aiohttp import ClientSession


tasks = []
url = "https://www.baidu.com/{}"
async def hello(url):
    async with ClientSession() as session:
        async with session.get(url) as response:
            response = await response.read()
            print(response)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(hello(url))

首先async def 關鍵字定義了這是個異步函數,await 關鍵字加在需要等待的操作前面,response.read()等待request響應,是個耗IO操作。然後使用ClientSession類發起http請求。

多鏈接異步訪問

如果我們需要請求多個URL該怎麼辦呢,同步的做法訪問多個URL只需要加個for循環就可以了。但異步的實現方式並沒那麼容易,在之前的基礎上需要將hello()包裝在asyncio的Future對象中,然後將Future對象列表作爲任務傳遞給事件循環

import time
import asyncio
from aiohttp import ClientSession

tasks = []
url = "https://www.baidu.com/{}"
async def hello(url):
    async with ClientSession() as session:
        async with session.get(url) as response:
            response = await response.read()
#            print(response)
            print('Hello World:%s' % time.time())

def run():
    for i in range(5):
        task = asyncio.ensure_future(hello(url.format(i)))
        tasks.append(task)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    run()
    loop.run_until_complete(asyncio.wait(tasks))

 輸出:

Hello World:1527754874.8915546
Hello World:1527754874.899039
Hello World:1527754874.90004
Hello World:1527754874.9095392
Hello World:1527754874.9190395

收集http響應

好了,上面介紹了訪問不同鏈接的異步實現方式,但是我們只是發出了請求,如果要把響應一一收集到一個列表中,最後保存到本地或者打印出來要怎麼實現呢,可通過asyncio.gather(*tasks)將響應全部收集起來,具體通過下面實例來演示。

import time
import asyncio
from aiohttp import ClientSession

tasks = []
url = "https://www.baidu.com/{}"
async def hello(url):
    async with ClientSession() as session:
        async with session.get(url) as response:
#            print(response)
            print('Hello World:%s' % time.time())
            return await response.read()

def run():
    for i in range(5):
        task = asyncio.ensure_future(hello(url.format(i)))
        tasks.append(task)
    result = loop.run_until_complete(asyncio.gather(*tasks))
    print(result)

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    run()

輸出:

Hello World:1527765369.0785167
Hello World:1527765369.0845182
Hello World:1527765369.0910277
Hello World:1527765369.0920424
Hello World:1527765369.097017
[b'<!DOCTYPE html>\r\n<!--STATUS OK-->\r\n<html>\r\n<head>\r\n......

異常解決

假如你的併發達到2000個,程序會報錯:ValueError: too many file descriptors in select()。報錯的原因字面上看是 Python 調取的 select 對打開的文件有最大數量的限制,這個其實是操作系統的限制,linux打開文件的最大數默認是1024,windows默認是509,超過了這個值,程序就開始報錯。這裏我們有三種方法解決這個問題:

1.限制併發數量。(一次不要塞那麼多任務,或者限制最大併發數量)

2.使用回調的方式

3.修改操作系統打開文件數的最大限制,在系統裏有個配置文件可以修改默認值,具體步驟不再說明了。

不修改系統默認配置的話,個人推薦限制併發數的方法,設置併發數爲500,處理速度更快。

#coding:utf-8
import time,asyncio,aiohttp


url = 'https://www.baidu.com/'
async def hello(url,semaphore):
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as response:
                return await response.read()


async def run():
    semaphore = asyncio.Semaphore(500) # 限制併發量爲500
    to_get = [hello(url.format(),semaphore) for _ in range(1000)] #總共1000任務
    await asyncio.wait(to_get)


if __name__ == '__main__':
#    now=lambda :time.time()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())
    loop.close()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章