我遇到了一个asyncIO问题。我想让我的程序在协同线正在运行的任务中做些什么,在协同线完成之后,退出。
我将我的问题简化为以下片段:
import time
import asyncio
async def long_task():
time.sleep(3)
return "DONE !"
def do_while_idle():
loop = asyncio.get_event_loop()
task = loop.create_task(long_task)
while not task.done():
time.sleep(1)
print("IDLE")
print(task.result())
do_while_idle()我想要这个输出:
IDLE
IDLE
IDLE
DONE !提前谢谢。
发布于 2020-04-28 20:21:43
作为MisterMiyagi points out,您必须等待asyncio.sleep()而不是调用time.sleep(),以及消除其他阻塞,例如将requests的用法替换为aiohttp。
要执行一些空闲代码,只要任务正在运行,就可以将空闲代码编写为一个无限循环,独立于主要任务。do_while_idle可以作为一个任务启动空闲循环,直接等待long_task(),然后取消空闲循环:
import asyncio
async def long_task():
await asyncio.sleep(3)
return "DONE !"
async def idle():
while True:
await asyncio.sleep(1)
print("IDLE")
async def do_while_idle():
idle_task = asyncio.create_task(idle())
print(await long_task())
idle_task.cancel()
asyncio.run(do_while_idle())发布于 2020-04-28 17:43:10
您可以这样处理:
import asyncio
async def do_while_idle():
for _ in range(3):
print("IDLE")
await asyncio.sleep(1)
return "Done stuff while idling"
async def long_task():
await asyncio.sleep(3)
return "DONE !"
async def main():
task = asyncio.create_task(long_task())
task2 = asyncio.create_task(do_while_idle())
done, _ = await asyncio.wait({task, task2})
if task in done:
task2.cancel()
print(task.result())
asyncio.run(main())空闲应该是另一个任务,这个片段等待long_task完成,并取消空闲任务。您还可以检查空闲和long_task是否都是这样完成的:
async def main():
task = asyncio.create_task(long_task())
task2 = asyncio.create_task(do_while_idle())
done, _ = await asyncio.wait({task, task2})
if task and task2 in done:
print(task.result(), task2.result())第一个代码段将给出您想要的结果:
IDLE
IDLE
IDLE
DONE !https://stackoverflow.com/questions/61485714
复制相似问题