4.定义task对象

1.定义task对象如下:

# 导入 Python 内置异步库 asyncio,用来实现协程、事件循环调度。
import asyncio

# async def:代表这是一个协程函数
async def execute(x):
    print('number:',x)  # 协程内部逻辑,等到被`await`的时候才会打印

async def main():  # `main` 也是协程函数,作为整个异步程序的入口。
    coroutine = execute(1) # 得到一个协程对象,赋值给变量 coroutine。
    print('coroutine',coroutine)  # 打印协程对象
    print('After calling execute')
    task = asyncio.create_task(coroutine) # 把协程包装成Task任务
    print('task:',task)  # 此时任务状态:`pending`(等待运行)
    await task  # 触发执行这个coroutine协程对象,等它完成再往下走
    print('task:', task)   # 此时任务状态:`finished`(运行结束)
    print('After calling loop')
  • 运行结果如下:
coroutine <coroutine object execute at 0x00000292DFE98E10>
After calling execute
task: <Task pending name='Task-2' coro=<execute() running at E:\Python\Python_demo\py_project01\异步爬虫\03.定义task对象.py:5>>
number: 1
task: <Task finished name='Task-2' coro=<execute() done, defined at E:\Python\Python_demo\py_project01\异步爬虫\03.定义task对象.py:5> result=None>
After calling loop
posted @ 2026-11-16 20:21  abner_pan  阅读(6)  评论(0)    收藏  举报