python 尝试启动异步任务时出错

ogq8wdun  于 2022-12-10  发布在  Python
关注(0)|答案(1)|浏览(152)

在我的start函数中,我运行了3个函数+ print。我想让我的create_task形成2个函数并同步执行它们,这就是现在正在发生的事情。同时我试图运行异步函数say_hi(),并且我希望它在开始时立即执行,而不等待其他函数完成,也不等待say_hi函数本身执行。我如何运行它?如果我删除await,我会得到一个错误:

RuntimeWarning: coroutine 'say_hi' was never awaited say_hi()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

密码:

import asyncio
from datetime import datetime

async def say_hi():
  task = asyncio.sleep(1)
  print("HI")
  await task

async def start():
  asyncio.create_task(write_file())
  await say_hi()
  asyncio.create_task(take_time(time=datetime.now()))
  print("hi")

async def main():
  tasks = [
    start(),
  ]
  await asyncio.gather(*tasks)

asyncio.run(main())
nfzehxib

nfzehxib1#

如果我没理解错的话,您可以使用另一个asyncio.gather来同时执行write_file()take_time()say_hi()任务:

import asyncio
from datetime import datetime

async def write_file():
    await asyncio.sleep(2)
    print("write file")

async def take_time(time):
    await asyncio.sleep(3)
    print("take time")

async def say_hi():
    await asyncio.sleep(1)
    print("HI")

async def start():
    t1 = asyncio.create_task(write_file())
    t2 = asyncio.create_task(say_hi())
    t3 = asyncio.create_task(take_time(time=datetime.now()))
    await asyncio.gather(t1, t2, t3)
    print("hi")

async def main():
    tasks = [
        start(),
    ]
    await asyncio.gather(*tasks)

asyncio.run(main())

印刷品:

HI
write file
take time
hi

相关问题