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

主頁 > 知識庫 > 淺談Python協程asyncio

淺談Python協程asyncio

熱門標簽:高德地圖標注是免費的嗎 無錫客服外呼系統一般多少錢 老人電話機器人 洪澤縣地圖標注 百度地圖標注位置怎么修改 大連crm外呼系統 梅州外呼業務系統 地圖標注視頻廣告 北京電信外呼系統靠譜嗎

一、協程

官方描述;
協程是子例程的更一般形式。 子例程可以在某一點進入并在另一點退出。 協程則可以在許多不同的點上進入、退出和恢復。 它們可通過 async def 語句來實現。 參見 PEP 492。

  • 協程不是計算機內部提供的,不像進程、線程,由電腦本身提供,它是由程序員人為創造的, 實現函數異步執行。
  • 協程(Coroutine),也可以被稱為微線程,是一種用戶太內的上下文切換技術,其實就是通過一個線程實現代碼塊相互切換執行。看上去像子程序,但執行過程中,在子程序內部可中斷,然后轉而執行別的子程序,在適當的時候再返回來接著執行。例如:
# 需要python3.7+
import asyncio


async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')

asyncio.run(main())

# 打印 "hello",等待 1 秒,再打印 "world"

注意:簡單地調用一個協程并不會使其被調度執行,

直接main() 調用會有問題:

RuntimeWarning: coroutine 'main' was never awaited
  main()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

def func1():
    print(1)
    ...
    print(2)
    
def func2():
    print(3)
    ...
    print(4)

func1()
func2() 

# 結果:1 2 3 4

實現協程的方法:

  • greenlet,早期模塊【不建議使用】
  • yield關鍵字,它是python的生成器,具有保存狀態,切換到其他函數去執行,再切換回原函數的功能。
  • asyncio裝飾器(python3.4引入)
  • async、await 關鍵字(python3.5)【推薦使用】

1.1 greenlet實現協程

# 第三方模塊,因此需要安裝

pip install greenlet
from greenlet import greenlet


def func1():
    print(1)
    gr2.switch()
    print(2)
    gr2.switch()


def func2():
    print(3)
    gr1.switch()
    print(4)


gr1 = greenlet(func1)
gr2 = greenlet(func2)

gr1.switch()

# 結果:1 3 2 4

1.2 yield關鍵字

def func1():
    yield 1
    yield from func2()
    yield 2


def func2():
    yield 3
    yield 4

f1 = func1()
for item in f1:
    print(item)
    
# 結果:1 3 2 4

1.3 asynico裝飾器

python3.4 及之后版本支持

DeprecationWarning: “@coroutine” decorator is deprecated since Python 3.8, use “async def”
翻譯:@coroutine"裝飾器自Python 3.8起已棄用,請使用"async def"代替

所以這個也不支持。

import asyncio

@asyncio.coroutine
def func1():
    print(1)
    yield from asyncio.sleep(2)  # 遇到IO耗時操作,自動切換到tasks中其他任務,比如:網絡IO,下載圖片
    print(2)

@asyncio.coroutine
def func2():
    print(3)
    yield from asyncio.sleep(2)  # 遇到IO耗時操作,自動切換到tasks中其他任務,比如:網絡IO,下載圖片
    print(4)

tasks = [
    asyncio.ensure_future(func1()),
    asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

# 結果: 1 3 2 4

1.4 async await 關鍵字

import asyncio


async def func1():
    print(1)
    await asyncio.sleep(2)  # 遇到IO耗時操作,自動切換到tasks中其他任務,比如:網絡IO,下載圖片
    print(2)


async def func2():
    print(3)
    await asyncio.sleep(2)  # 遇到IO耗時操作,自動切換到tasks中其他任務,比如:網絡IO,下載圖片
    print(4)

tasks = [
    asyncio.ensure_future(func1()),
    asyncio.ensure_future(func2())
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

二、協程的意義

充分利用線程。在一個線程中如果遇到IO等待時間線程不會一直等待,利用空閑時間再去干點其他事情。

以下載三張圖片為例:

普通方式(同步)下載:

import time
import requests

def download_image(url, img_name):
    print("開始下載:", url)
    # 發送網絡請求,下載圖片
    response = requests.get(url)
    print("下載完成")
    # 圖片保存到本地文件
    file_name = str(img_name) + '.png'
    with open(file_name, mode='wb') as file:
        file.write(response.content)

if __name__ == '__main__':
    start = time.time()
    url_list = [
        'https://tse4-mm.cn.bing.net/th/id/OIP.866vRxQ8QvyDsrUuXiu7qwHaNK?w=182h=324c=7o=5pid=1.7',
        'https://tse2-mm.cn.bing.net/th/id/OIP.HUcWtoYPG-z2pu4ityajbAHaKQ?w=182h=252c=7o=5pid=1.7',
        'https://tse2-mm.cn.bing.net/th/id/OIP.MvncR0-Pt9hVxKTdrvD9dAHaNK?w=182h=324c=7o=5pid=1.7',
        'https://tse1-mm.cn.bing.net/th/id/OIP._nGloaeMWbL7NB7Lp6SnXQHaLH?w=182h=273c=7o=5pid=1.7',
        ]
    img_name = 1
    for item in url_list:
        download_image(item, img_name)
        img_name += 1
    end = time.time()
    print(end - start)
    
 # 最終時間:7.25s

協程方式(異步)下載:

import aiohttp
import asyncio
import time


async def fetch(session, url):
    print("發送請求:", url)

    async with session.get(url, verify_ssl=False) as response:
        content = await response.content.read()
        file_name = url.rsplit('_')[-1]
        # print(file_name)
        with open(file_name, mode='wb') as file_object:
            file_object.write(content)
        print("下載完成")


async def main():
    async with aiohttp.ClientSession() as session:
        url_list = [
            'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
            'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
            'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
            'https://www3.autoimg.cn/newsdfs/g26/M02/35/A9/120x90_0_autohomecar__ChsEe12AXQ6AOOH_AAFocMs8nzU621.jpg',
        ]
        tasks = [asyncio.ensure_future(fetch(session, url)) for url in url_list]
        await asyncio.wait(tasks)

if __name__ == '__main__':
    start = time.time()
    asyncio.get_event_loop().run_until_complete(main())
    end = time.time()
    print(end - start)
    
# 結果:0.05s

到此這篇關于淺談Python協程的文章就介紹到這了,更多相關Python協程內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • Python協程asyncio異步編程筆記分享
  • 深入理解python協程
  • 淺談Python協程
  • python協程用法實例分析
  • javascript實現鼠標拖尾特效
  • JavaScript循環遍歷的24個方法,你都知道嗎
  • JavaScript實現簡單拖拽效果
  • JavaScript 數組去重詳解
  • 簡單談談JavaScript變量提升
  • Python 協程與 JavaScript 協程的對比

標簽:泉州 怒江 安慶 洛陽 長春 清遠 吉林 岳陽

巨人網絡通訊聲明:本文標題《淺談Python協程asyncio》,本文關鍵詞  淺談,Python,協程,asyncio,淺談,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《淺談Python協程asyncio》相關的同類信息!
  • 本頁收集關于淺談Python協程asyncio的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 文水县| 桓台县| 芦溪县| 河北省| 广汉市| 南雄市| 尚义县| 甘德县| 张家口市| 灌阳县| 军事| 华池县| 尚志市| 博爱县| 老河口市| 青河县| 卓资县| 兖州市| 民和| 开封县| 四平市| 弥勒县| 灵宝市| 临潭县| 遵化市| 恭城| 敦化市| 桦川县| 岢岚县| 类乌齐县| 扎兰屯市| 历史| 内丘县| 南木林县| 巩义市| 武鸣县| 武邑县| 米泉市| 桦川县| 宁强县| 泸水县|