首页 > 解决方案 > 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())

标签: pythonpython-asyncio

解决方案


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

推荐阅读