【问题标题】:Python asyncio.gather returns NonePython asyncio.gather 返回无
【发布时间】:2019-11-20 20:14:13
【问题描述】:

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

正如您在下面的工作函数内的 cmets 中看到的那样,我一完成就会收到响应。我想得到有序的响应,这就是我使用 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)

【问题讨论】:

    标签: python http aiohttp python-asyncio


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2018-04-06
      • 2014-02-23
      • 2013-07-27
      相关资源
      最近更新 更多