【问题标题】:Asyncio.sleep blocking the rest of the function [duplicate]Asyncio.sleep 阻塞了函数的其余部分[重复]
【发布时间】:2021-10-14 03:42:15
【问题描述】:

由于 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())

【问题讨论】:

  • 当然是阻塞,这就是sleep的目的。但是 1 秒后它会继续,if 事件循环仍在运行,这不是你的情况。
  • @mkrieger1 一秒钟后它没有继续。这就是我在这里问的原因
  • 任务一提交到循环程序就结束了,它们并没有完成,只是开始。您实际上需要等待它们完成才能获得预期的输出。

标签: python python-asyncio


【解决方案1】:

看起来您创建了任务但没有执行它们。用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

【讨论】:

  • 如果我将 print(0) 移到 asyncio.sleep 的上方,它会打印出来。所以 asyncio.create_task 调用该函数。无论如何我会尝试你的建议。
  • async def get_histories(): tasks = [] for parite in parite_list: tasks.append(asyncio.create_task(parite.getHistory())) await asyncio.gather(*tasks) asyncio.run( get_histories()) 我确实喜欢这个。但是这一次直到睡眠它是异步的,但是函数的其余部分是非异步的。好奇怪。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 2012-01-15
相关资源
最近更新 更多