简体   繁体   English

Python asyncio.gather 返回无

[英]Python asyncio.gather returns None

I'm using Python asyncio to implement a fast http client.我正在使用 Python asyncio 来实现快速 http 客户端。

As you can see in the comments below inside the worker function I get the responses as soon as they are finished.正如您在工人 function 内部的评论中看到的那样,我一完成就会收到回复。 I would like to get the responses ordered and this is why I'm using asyncio.gather.我想得到有序的响应,这就是我使用 asyncio.gather 的原因。

Why is it returning None?为什么它返回无? Can anybody help?有人可以帮忙吗?

Thank you so much!太感谢了!

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)

Your function run doesn't return nothing explicitly, so it returns None implicitly.您的 function run不会显式返回任何内容,因此它会隐式返回None Add return statement and you'll get a result添加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