在 Python Asyncio 上,我正在尝试 return 从一个函数到另一个函数的值

On Python Asyncio I am trying to return a value from one function to another

在 Python Asyncio 上,我正在尝试 return 从一个函数到另一个函数的值。

所以当 func "check" 末尾的 if 语句为 True 时,returned 将值

将执行“打印”功能。

async def check(i):
        async with aiohttp.ClientSession() as session:
            url = f'https://pokeapi.co/api/v2/pokemon/{i}'
            async with session.get(url) as resp:
                data = await resp.text()
                if data['state'] == 'yes':
                    return data['state']
                ## how do i keeping the structre of the asyncio and pass this result to the "print" function



async def print(here should be the return of "check" funtion is there is):
        print()
        await asyncio.sleep(0)


async def main():
    for i in range(0,5):
        await asyncio.gather(check(i),
                             print() )

谢谢 (-:

简单的解决方案:不要运行这两个功能并发。其中一个显然需要另一个来完成。

async def print_it(i):
    value = await check(i)
    if value is not None:
        print(value)

当函数完成其最后一条语句时,即当 return data['state'] 未在 check() 中执行时,存在隐式 return None。在这种情况下,不会打印任何内容 - 如果不正确,请调整代码。

当然,你应该只启动 print_it 个协程,而不启动 checks.


如果出于某种原因确实需要 运行 这些函数并发,请使用 Queue。生产者将数据放入队列,消费者获取可用的值。

您的代码将 运行 同步处理所有内容。您需要稍微重组一下才能看到 asyncio 的任何价值。

async def check(i):
    async with aiohttp.ClientSession() as session:
        url = f'https://pokeapi.co/api/v2/pokemon/{i}'
        async with session.get(url) as resp:
            data = await resp.text()
            if data['state'] == 'yes':
                return data['state']

async def main():
    aws = [check(i) for i in range(5)]
    results = await asyncio.gather(*aws)
    for result in results:
        print(result)

这将使您的 aiohttp 请求异步 运行。假设 print 实际上只是内置函数的包装器,您不需要它,只需使用内置函数即可。

但是,如果 print 实际上做了其他事情,您应该使用 asyncio.as_completed 而不是 asyncio.gather

async def my_print(result):
    print(result)
    await asyncio.sleep(0)

async def main():
    aws = [check(i) for i in range(5)]
    for coro in asyncio.as_completed(aws):
        result = await coro
        await my_print(result)