簡體   English   中英

Python asyncio.gather 返回無

[英]Python asyncio.gather returns None

我正在使用 Python asyncio 來實現快速 http 客戶端。

正如您在工人 function 內部的評論中看到的那樣,我一完成就會收到回復。 我想得到有序的響應,這就是我使用 asyncio.gather 的原因。

為什么它返回無? 有人可以幫忙嗎?

太感謝了!

import time
import aiohttp
import asyncio

MAXREQ = 100
MAXTHREAD = 500
URL = 'https://google.com'
g_thread_limit = asyncio.Semaphore(MAXTHREAD)


async def worker(session):
    async with session.get(URL) as response:
        await response.read()   #If I print this line I get the responses correctly

async def run(worker, *argv):
    async with g_thread_limit:
        await worker(*argv)

async def main():
    async with aiohttp.ClientSession() as session:
        await asyncio.gather(*[run(worker, session) for _ in range(MAXREQ)])

if __name__ == '__main__':
    totaltime = time.time()
    print(asyncio.get_event_loop().run_until_complete(main()))   #I'm getting a None here
    print (time.time() - totaltime)

您的 function run不會顯式返回任何內容,因此它會隱式返回None 添加return語句,你會得到一個結果

async def worker(session):
    async with session.get(URL) as response:
        return await response.read()


async def run(worker, *argv):
    async with g_thread_limit:
        return await worker(*argv)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM