简体   繁体   English

如何使用 asyncio.gather 返回一个值?

[英]How to return a value with asyncio.gather?

I want to Send a Message to multiple Servers at once.我想一次向多个服务器发送消息。 with the help of Stackoverflow I came up with a solution like this here.在 Stackoverflow 的帮助下,我在这里想出了一个这样的解决方案。 But I don't know how to get this code Working.但我不知道如何让这段代码工作。

async def sendmessages(embed):
    ids = []
    for channel in fetchedchannel:
        m = await channel.send(embed = embed)
        ids.append(m.id)
    return ids

ids = []
try:
    ids = await asyncio.gather(sendmessage(embed))
except:
    pass
print(ids)

The variable fetchedchannel is a list with all the Channels the message should be sent to.变量 fetchedchannel 是一个列表,其中包含消息应发送到的所有通道。

The output I expect is something like [541654984561689, 848594981654894, 549846898948489, 84869489785156489] What I get is []我期望的 output 类似于[541654984561689, 848594981654894, 549846898948489, 84869489785156489]我得到的是[]

To schedule an initial coroutine from your script, you have to use asyncio.run.要从脚本中安排初始协程,您必须使用 asyncio.run。 However, your code will still send the messages sequentially as that is just done in that for loop one by one.但是,您的代码仍将按顺序发送消息,因为这只是在 for 循环中一一完成。 Also gather is not needed as you are only awaiting a single coroutine.也不需要gather ,因为您只等待一个协程。 If that is what you want, you can just do res = await sendmessages(embed).如果这是你想要的,你可以做 res = await sendmessages(embed)。

If you actually want to have those sends to run concurrently, you might want to change your code roughly like如果你真的想让这些发送同时运行,你可能想大致改变你的代码

import asyncio

async def main():
    return await asyncio.gather(*(channel.send(embed = embed) for channel in fetchedchannel))

result = asyncio.run(main())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM