gpt4 book ai didi

Python asyncio.gather 返回 None

转载 作者:行者123 更新时间:2023-12-01 00:21:10 24 4
gpt4 key购买 nike

我正在使用 Python asyncio 来实现快速的 http 客户端。

正如您在工作函数内下面的评论中看到的那样,我会在完成后立即收到回复。我想获得有序的响应,这就是我使用 asyncio.gather 的原因。

为什么它返回 None?有人可以帮忙吗?

非常感谢!

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)

最佳答案

您的函数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)

关于Python asyncio.gather 返回 None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58962620/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com