Asyncio.sleep 阻止函数的其余部分
Asyncio.sleep blocking the rest of the function
由于 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
由于 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