Python创建子协程
时间: 2024-02-02 07:43:35 浏览: 15
在Python中,可以使用asyncio库创建协程和子协程。下面是一个例子,演示了如何创建一个子协程:
```python
import asyncio
async def parent_coroutine():
print('Parent coroutine started')
await asyncio.sleep(1)
print('Creating child coroutine')
task = asyncio.create_task(child_coroutine())
await task
print('Child coroutine finished')
async def child_coroutine():
print('Child coroutine started')
await asyncio.sleep(2)
print('Child coroutine finished')
asyncio.run(parent_coroutine())
```
在这个例子中,我们首先定义了一个父协程 `parent_coroutine()` 和一个子协程 `child_coroutine()`。在父协程中,我们先打印一条消息,然后等待1秒钟。接着,我们创建一个子协程任务 `task`,并使用 `await` 关键字等待该任务完成。在子协程中,我们打印一条消息,然后等待2秒钟。当子协程完成后,我们回到父协程中,打印出一条完成消息。
在运行这个程序时,你会看到如下输出:
```
Parent coroutine started
Creating child coroutine
Child coroutine started
Child coroutine finished
Child coroutine finished
```
可以看到,子协程先于父协程结束,但父协程会等待子协程完成后再继续执行。这是因为我们在父协程中使用了 `await` 关键字等待子协程任务完成。