温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

在python里如何创建一个任务

发布时间:2020-07-30 14:30:09 来源:亿速云 阅读:191 作者:小猪 栏目:开发技术

小编这次要给大家分享的是在python里如何创建一个任务,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

与事件循环进行交互,最基本的方式就是任务,任务封装了协程和自动跟踪它的状态。任务是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

看完这篇关于在python里如何创建一个任务的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI