【问题标题】:Python: How to obtain return value from only one function (out of several executed with asyncio.gather)Python:如何仅从一个函数获取返回值(在使用 asyncio.gather 执行的几个函数中)
【发布时间】:2021-01-18 09:04:31
【问题描述】:

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_messagescheck_messages() 回来,但 interval() 甚至不返回值,所以它是不需要的。有没有比创建_interval 更好的方法?

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    你做对了,你不需要改变任何东西。如果太长,您可以将_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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2021-02-07
      • 2017-12-14
      • 2014-06-28
      • 2018-10-21
      • 1970-01-01
      • 2013-03-31
      相关资源
      最近更新 更多