关于asyncio模块,如何获取子例程的返回值?

2024-05-08 16:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

已打开协同程序的当前事件循环。在协程对象内部,创建一个新的协程对象并将其注册到事件循环中

问题:如何获取sub-coroutine的返回值

我想得到func_first的返回值

import asyncio
import time


async def func_first(values):
    await asyncio.sleep(2)
    print('out: func_first')
    return values


async def func_second():
    s = asyncio.create_task(func_first(100))
    await asyncio.sleep(3)
    print('out: func_second')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    s = time.time()
    loop.run_until_complete(func_second())
    print('TIME:', time.time()-s)

Tags: 对象importloopasyncioasynctimedef事件
2条回答

我在这里找到了答案: enter link description here

asyncio.Queue可以得到数据,似乎我对这个模块还不太了解。哈哈

在您的代码中,只需将waits添加到print语句中。事实上,这比那更容易:不要费心去创建一个任务;只需等待函数并直接打印值。此代码显示两种方法:

import asyncio
import time

async def func_first(values):
    await asyncio.sleep(2)
    print('out: func_first')
    return values

async def func_second():
    s = asyncio.create_task(func_first(100))
    await asyncio.sleep(3)
    print('out: func_second', await s)

async def func_third():
    print('out: func_third', await func_first(101))

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    s = time.time()
    loop.run_until_complete(func_second())
    print('TIME:', time.time()-s)
    loop.run_until_complete(func_third())
    print('TIME:', time.time()-s)

结果:

out: func_first
out: func_second 100
TIME: 3.062396764755249
out: func_first
out: func_third 101
TIME: 5.09357476234436
>>> 

相关问题 更多 >

    热门问题