python - Asyncio.sleep 阻塞了函数的其余部分
问题描述
由于 asyncio.sleep,函数无法传递到下一行。还有其余的代码,但我将只分享 3 行。它解释了一切。控制台不会将 0 打印到控制台。如果我将 print(0) 移到 asyncio.sleep 上方,它会打印到控制台。
async def getHistory(self):
logging.info(f"Getting history for {self.parite}...")
await asyncio.sleep(1)
print(0)
async def get_histories():
for parite in parite_list:
asyncio.create_task(parite.getHistory())
asyncio.run(get_histories())
解决方案
看起来您创建了任务但没有执行它们。用asyncio.gather试试这个:
import asyncio
import logging
async def getHistory(num):
print(f"Getting history for {num}...")
await asyncio.sleep(1)
print(num)
async def get_histories():
await asyncio.gather(
asyncio.create_task(getHistory(1)),
asyncio.create_task(getHistory(2)),
asyncio.create_task(getHistory(3))
)
asyncio.run(get_histories())
结果:
% python asdf.py
Getting history for 1...
Getting history for 2...
Getting history for 3...
1
2
3
推荐阅读
- spring-boot - 为 Couchbase 应用程序添加事务管理器。在用于 Junit 测试的 SpringBoot 2 应用程序中
- angularjs - 如何将第二个 ngrepeat 中的值放入 $filter
- ios - 强制更新具有另一个 pod 依赖关系的 POD
- symfony - Symfony4:UniqueEntity 约束不适用于 GUID 字段(相关实体)
- javascript - ChartJS - 设置最小值。对于 Y 轴
- html - 输入字段 maxlength 不适用于 Tizen Studio 上的文本类型
- python - 尽管安装了 conda facebook sdk,但 Spyder ''导入 Facebook 错误''
- python-3.x - Selenium .click() 不起作用。接收错误“列表”对象没有属性“点击”
- r - 在 R 中基于另一个变量创建一个变量
- python - PasswordResetConfirmView 无法正常工作?