[英]Python: why use AsyncIO if not with 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.