[英]Python: How to obtain return value from only one function (out of several executed with asyncio.gather)
What is a good way to run functions with asyncio.gather
and get the return value from only one of the executed functions?什么是使用
asyncio.gather
运行函数并仅从一个已执行函数中获取返回值的好方法? This might be more of a novice Python syntax question than it has to do with asyncio
per se but my example script below uses it.这可能更像是一个新手 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
I basically want received_messages
back from check_messages()
, but interval()
doesn't even return a value so it is unneeded.我基本上希望从
check_messages()
返回received_messages
,但interval()
甚至不返回一个值,所以它是不需要的。 Is there a nicer way of doing this than having to create _interval
?有没有比创建
_interval
更好的方法?
You are doing it right, you don't need to change anything.你做对了,你不需要改变任何东西。 You can shorten
_interval
to _
if it's too long as it is.如果
_interval
,您可以将其缩短为_
。 You can avoid the other variable completely with received_messages = (await asyncio.gather(interval(), check_messages()))[1]
, but that's just less readable.您可以使用
received_messages = (await asyncio.gather(interval(), check_messages()))[1]
完全避免其他变量,但这只是可读性较差。
Another option is not to use gather
at all, but spawn two tasks and await them.另一种选择是根本不使用
gather
,而是生成两个任务并等待它们。 It doesn't lead to less code, but here it is for completeness:它不会导致更少的代码,但这里是为了完整性:
asyncio def main():
t1 = asyncio.create_task(interval())
t2 = asyncio.create_task(messaages())
await t1
received_messages = await t2
if received_messages:
# process them
Note that the above code will run interval()
and messages()
in parallel, despite the use of await
, because both are spawned as tasks prior to the first await
- see this answer for a more detailed explanation.请注意,尽管使用了
await
,上述代码仍将并行运行interval()
和messages()
,因为两者都是在第一次await
之前作为任务生成的 - 请参阅此答案以获得更详细的解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.