Asyncio 如何收集可变数量的协程?

Asyncio how to gather a variable amount of corroutines?

我正在编写一个程序,该程序有时需要收集未知数量的协程,该程序管理多个帐户,并且每个帐户都有一个客户端协程,我如何收集未知数量的客户端帐号?

这是我当前的收集功能。

loop.run_until_complete(asyncio.gather(
    main_client.start(token),
    account1.client.start(account.credentials),
    #More accounts should go here
    main_player_control.loop()
    #If possible, also would like to have multiple player controls
))

作为@Vincent ,您可以使用 * 函数调用语法将可变数量的协程传递给 asyncio.gather。或者,您可以调用 asyncio.wait,它接受一个列表。

看代码,一个gather是否正确也不明显。 gather 一次启动所有协程,即与主循环并行运行授权协程。可能是某种 intialization/authorization 需要首先发生,然后是控制循环。在那种情况下,像这样的 main 协同程序可能会更好地为您服务:

async def main(main_client, token, accounts, main_player):
    # authorize the main client
    await main_client.start(token),
    # authorize all the accounts in parallel
    await asyncio.wait(account.client.start(account.credentials)
                       for account in accounts)
    # once the above is complete, start the main loop
    await main_player_control.loop()

loop.run_until_complete(main(main_client, token, accounts, main_player))