python - Python:如何仅从一个函数中获取返回值(在使用 asyncio.gather 执行的几个函数中)
问题描述
什么是运行函数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_messages
从 回来check_messages()
,但interval()
甚至不返回一个值,所以它是不需要的。有没有比必须创建更好的方法来做到这一点_interval
?
解决方案
你做对了,你不需要改变任何东西。如果它太长,你可以缩短_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
请注意,尽管使用了 ,上述代码仍将并行运行interval()
,因为两者都是在第一个之前作为任务生成的- 请参阅此答案以获得更详细的解释。messages()
await
await
推荐阅读
- java - Spring Boot 集成测试。如何测试“删除”方法?
- apache-spark - 使用 PySpark 以不同方式处理每一行的空值
- css - 在具有背景图像的列中进行两列转换的最佳方法是什么?
- c++ - Boost::interprocess: scoped_lock 在崩溃后似乎无法获取
- r - R日期比较使用循环
- asp.net-core - 如何测试从代理获取数据的微服务
- php - CodeIgniter 4:“BadMethodCallException”试图插入或更新数据
- python - 连接 url + dtype:字符串
- python - 如何在列表之外的字典中合并键?
- java - 在 Docker 中运行的应用程序看不到该文件