我正在使用Python asyncio实现一个快速的http客户端。
正如您在worker函数中下面的注释中所看到的,我在完成后立即得到响应。我希望得到的回复是有序的,这就是我使用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)发布于 2019-11-21 04:18:00
您的函数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)https://stackoverflow.com/questions/58962620
复制相似问题