我可以在 Python 中启动协程而不等待阻塞吗?

Can I start a coroutine in Python without the blocking await?

这里是示例代码

async def washing():
  await asyncio.sleep(3)
  print("All washed!")

async def myloop():
  while 1:
    await washing() #Is there an alternative to start washing coroutine?
    print("start washing...")
    await asyncio.sleep(5)

asyncio.run(myloop())

显然我会得到“全部洗净!”然后打印出“开始洗涤...”,因为等待正在阻塞 - 它不会继续执行,直到命令执行完毕。

但我要的是反过来,先“开始洗”

我可以以非阻塞方式启动清洗协程并继续执行下一个命令(例如打印)吗?这比简单的谁先打印的问题严重得多,它是关于是否可以任意创建一个辅助协程。在这种阻塞方式下,虽然有两个async函数,但它们不是运行并行,而是顺序,并且永远锁定在一个有效的协程中。

如果您希望某些异步任务并行工作,请使用 asyncio.create_task

import asyncio


async def washing():
    await asyncio.sleep(3)
    print("All washed!")


async def myloop():
    while 1:
        # create Task to change the app flow
        asyncio.create_task(washing())
        print("start washing...")
        await asyncio.sleep(5)


if __name__ == '__main__':
    asyncio.run(myloop())

请注意,如果 myloop 在清洗 Task 之前完成,您将永远无法获得该 Task 的结果。