在python里创建一个任务(Task)实例
作者:caimouse 时间:2023-09-12 23:24:16
与事件循环进行交互,最基本的方式就是任务,任务封装了协程和自动跟踪它的状态。任务是Future类的子类,所以其它协程可以等待任务完成,或当这些任务完成获取返回结果。
在这里通过create_task()函数来创建一个任务实例,然后事件循环就运行这个任务,直到这个任务返回为止:
import asyncio
async def task_func():
print('in task_func')
return 'the result'
async def main(loop):
print('creating task')
task = loop.create_task(task_func())
print('waiting for {!r}'.format(task))
return_value = await task
print('task completed {!r}'.format(task))
print('return value: {!r}'.format(return_value))
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(event_loop))
finally:
event_loop.close()
结果输出如下:
creating task
waiting for <Task pending coro=<task_func() running at D:\work\csdn\python_Game1\example\asyncio_create_task.py:4>>
in task_func
task completed <Task finished coro=<task_func() done, defined at D:\work\csdn\python_Game1\example\asyncio_create_task.py:4> result='the result'>
return value: 'the result'
补充知识:python里创建任务执行一半时取消任务执行
下例子来演示创建任务执行一半时取消任务执行,这时会抛出异常CancelledError,同时也提供了一个机会来删除占用资源等等:
import asyncio
async def task_func():
print('in task_func, sleeping')
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
print('task_func was canceled')
raise
return 'the result'
def task_canceller(t):
print('in task_canceller')
t.cancel()
print('canceled the task')
async def main(loop):
print('creating task')
task = loop.create_task(task_func())
loop.call_soon(task_canceller, task)
try:
await task
except asyncio.CancelledError:
print('main() also sees task as canceled')
event_loop = asyncio.get_event_loop()
try:
event_loop.run_until_complete(main(event_loop))
finally:
event_loop.close()
结果输出如下:
creating task
in task_func, sleeping
in task_canceller
canceled the task
task_func was canceled
main() also sees task as canceled
来源:https://blog.csdn.net/caimouse/article/details/77895432
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
配置python连接oracle读取excel数据写入数据库的操作流程
![](https://img.aspxhome.com/file/2023/6/109436_0s.png)
django 文件上传功能的相关实例代码(简单易懂)
![](https://img.aspxhome.com/file/2023/8/105318_0s.png)
14个出色的jQuery导航菜单实例教程
![](https://img.aspxhome.com/file/UploadPic/20101/11/094104n8w-71s.jpg)
查询mysql中执行效率低的sql语句的方法
python3 pygame实现接小球游戏
![](https://img.aspxhome.com/file/2023/3/98863_0s.png)
python实现k-means聚类算法
![](https://img.aspxhome.com/file/2023/4/120604_0s.jpg)
实现两个文本框同时输入的实例
python 查找字符串是否存在实例详解
使用Python画了一棵圣诞树的实例代码
![](https://img.aspxhome.com/file/2023/2/66402_0s.png)
BigPipe:高性能的"流水线技术"网页
![](https://img.aspxhome.com/file/UploadPic/201011/2/01-84s.jpg)
使用Python求解最大公约数的实现方法
Python使用Flask框架同时上传多个文件的方法
解决Python import .pyd 可能遇到路径的问题
![](https://img.aspxhome.com/file/2023/2/97652_0s.jpg)
PyCharm 设置SciView工具窗口的方法
![](https://img.aspxhome.com/file/2023/1/68961_0s.jpg)
python中requests小技巧
![](https://img.aspxhome.com/file/2023/1/135251_0s.png)
MacOS中 VSCode 安装 GO 插件失败问题的快速解决方法
关于base64编码的原理及实现方法分享
![](https://img.aspxhome.com/file/2023/6/132276_0s.gif)
零基础学习python偏函数语法的推导方法步骤
Python如何使用ElementTree解析xml
![](https://img.aspxhome.com/file/2023/0/130800_0s.png)