如何创建一个有返回值的异步任务?

6 python return async-await python-asyncio telethon

我正在弄清楚如何返回 list[]asyncio 我知道asyncio.gather可以帮助我,但现在有很多方法我很困惑。如何从 main() 返回值?感谢

async def wait_until(dt):
    # sleep until the specified datetime
    now = datetime.now()
    await asyncio.sleep((dt - now).total_seconds())

async def run_at(dt, coro):
    await wait_until(dt)
    return await coro

async def main():
    test=[]
    async for message in client.iter_messages(channel):
        test.append(message)
        return test


loop = asyncio.get_event_loop()
loop.create_task(run_at(datetime(2020, 12, 29, 19, 17),main()))
loop.run_until_complete(asyncio.gather(*[main()]))
# How to get test[] or How to pass it to another task?
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)

Lon*_*ami 5

asyncio.gather文档中:

\n
\n

如果所有可等待项均成功完成,则结果是返回值的聚合列表。结果值的顺序对应于 aws 中可等待的顺序。

\n
\n

asyncio.loop.run_until_complete文档中:

\n
\n

返回 Future\xe2\x80\x99s 结果或引发异常。

\n
\n

因此gatherasync def返回所有传递的结果,并run_until_complete运行循环将可等待“转换”为结果。基本上,返回值是通过以下方式传递的:

\n
results = loop.run_until_complete(asyncio.gather(*[main()]))\ntests = results[0]\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,gather仅使用一项是多余的,因为它相当于仅使用该一项:

\n
tests = loop.run_until_complete(main())\n
Run Code Online (Sandbox Code Playgroud)\n

如果您想在不使用全局变量的情况下通信两个独立的任务,您可能需要使用asyncio.Queue, 并将相同的队列实例提供给两个任务async def作为输入参数。一个将put“消息”,另一个将“get消息”。

\n

您可以将其与waitgathercreate_task等结合起来,几乎可以完成您需要的一切。

\n