在python里創(chuàng)建一個任務(wù)(Task)實例
與事件循環(huán)進(jìn)行交互,最基本的方式就是任務(wù),任務(wù)封裝了協(xié)程和自動跟蹤它的狀態(tài)。任務(wù)是Future類的子類,所以其它協(xié)程可以等待任務(wù)完成,或當(dāng)這些任務(wù)完成獲取返回結(jié)果。
在這里通過create_task()函數(shù)來創(chuàng)建一個任務(wù)實例,然后事件循環(huán)就運行這個任務(wù),直到這個任務(wù)返回為止:
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()
結(jié)果輸出如下:
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里創(chuàng)建任務(wù)執(zhí)行一半時取消任務(wù)執(zhí)行
下例子來演示創(chuàng)建任務(wù)執(zhí)行一半時取消任務(wù)執(zhí)行,這時會拋出異常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()
結(jié)果輸出如下:
creating task
in task_func, sleeping
in task_canceller
canceled the task
task_func was canceled
main() also sees task as canceled
以上這篇在python里創(chuàng)建一個任務(wù)(Task)實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解python selenium 爬取網(wǎng)易云音樂歌單名
這篇文章主要介紹了python selenium爬取網(wǎng)易云音樂歌單名,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03

