首页 > 解决方案 > Python:如何仅从一个函数中获取返回值(在使用 asyncio.gather 执行的几个函数中)

问题描述

什么是运行函数asyncio.gather并仅从一个已执行函数中获取返回值的好方法?这可能更像是一个新手 Python 语法问题,而不是它asyncio本身,但我下面的示例脚本使用它。

async def interval():
    await asyncio.sleep(10)

async def check_messages():
    received_messages = await check_for_new_messages()
    return received_messages

asyncio def main():
    _interval, received_messages = await asyncio.gather(interval(), check_messages())
    if received_messages:
        # process them

我基本上想received_messages从 回来check_messages(),但interval()甚至不返回一个值,所以它是不需要的。有没有比必须创建更好的方法来做到这一点_interval

标签: pythonpython-asyncio

解决方案


你做对了,你不需要改变任何东西。如果它太长,你可以缩短_interval到。_您可以使用 完全避免其他变量received_messages = (await asyncio.gather(interval(), check_messages()))[1],但这只是可读性较差。

另一种选择是根本不使用gather,而是生成两个任务并等待它们。它不会导致更少的代码,但这里是为了完整性:

asyncio def main():
    t1 = asyncio.create_task(interval())
    t2 = asyncio.create_task(messaages())
    await t1
    received_messages = await t2
    if received_messages:
        # process them

请注意,尽管使用了 ,上述代码仍将并行运行interval(),因为两者都是在第一个之前作为任务生成的- 请参阅此答案以获得更详细的解释。messages()awaitawait


推荐阅读