前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >在python里创建一个任务(Task)实例

在python里创建一个任务(Task)实例

作者头像
砸漏
发布2020-11-02 16:16:35
9340
发布2020-11-02 16:16:35
举报
文章被收录于专栏:恩蓝脚本

与事件循环进行交互,最基本的方式就是任务,任务封装了协程和自动跟踪它的状态。任务是Future类的子类,所以其它协程可以等待任务完成,或当这些任务完成获取返回结果。

在这里通过create_task()函数来创建一个任务实例,然后事件循环就运行这个任务,直到这个任务返回为止:

代码语言:javascript
复制
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,同时也提供了一个机会来删除占用资源等等:

代码语言:javascript
复制
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

以上这篇在python里创建一个任务(Task)实例就是小编分享给大家的全部内容了,希望能给大家一个参考。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档